Does Python have a finally
equivalent for its if/else
statements, similar to its try/except/finally
statements? Something that would allow us to simplify this:
if condition1:
do stuff
clean up
elif condition2:
do stuff
clean up
elif condition3:
do stuff
clean up
...
...
to this:
if condition1:
do stuff
elif condition2:
do stuff
elif condition3:
do stuff
...
...
finally:
clean up
Where finally
would only be called only after a condition was met and its 'do stuff' run? Conversely, if no condition was met, the finally
code would not be run.
I hate to spout blasphemy, but the best way I can describe it is there being a GOTO
statement at the end of each block of 'do stuff' that led to finally
.
Essentially, it works as the opposite of an else
statement. While else
is only run if no other conditions are met, this would be ran ONLY IF another condition was met.
A little late to the party, but see the question has been active recently.
Usually I would make a context manager like this
And then you can use it like this
Is this hideous?
How about this?
Honestly, I hate both of these
It can be done totally non-hackily like this:
In some ways, not as convenient, as you have to use a separate function. However, good practice to not make too long functions anyway. Separating your logic into small easily readable (usually maximum 1 page long) functions makes testing, documenting, and understanding the flow of execution a lot easier.
One thing to be aware of is that the
finally
clause will not get run in event of an exception. To do that as well, you need to addtry:
stuff in there as well.Like this:
Caveats are of course that your condition keys have to be unique and hashable. You can get around this by using a different data structure.
Your logic is akin to this:
Ugly, but it is what you asked
you can use try
the exception is raised but the cleanup is done