'Finally' equivalent for If/Elif statements in Python

It can be done totally non-hackily like this:

def function(x,y,z):
    if condition1:
        blah
    elif condition2:
        blah2
    else:
        return False

    #finally!
    clean up stuff.

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 add try: stuff in there as well.


you can use try

try:
    if-elif-else stuff
finally:
    cleanup stuff

the exception is raised but the cleanup is done


Your logic is akin to this:

cleanup = True
if condition1:
    do stuff
elif condition2:
    do stuff
elif condition3:
    do stuff
....
else:
    cleanup = False

if cleanup:
    do the cleanup

Ugly, but it is what you asked

Tags:

Python

Finally