0%

Finally equivalent for If/Elif statements in Python

❓ 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:

1
2
3
4
5
6
7
8
9
10
11
if condition1:
do stuff
clean up
elif condition2:
do stuff
clean up
elif condition3:
do stuff
clean up
...
...

to this:

1
2
3
4
5
6
7
8
9
10
if condition1:
do stuff
elif condition2:
do stuff
elif condition3:
do stuff
...
...
finally:
clean up

✔️ It can be done totally non-hackily like this:

1
2
3
4
5
6
7
8
9
10
def function(x,y,z):
if condition1:
blah
elif condition2:
blah2
else:
return False

#finally!
clean up stuff.