'Finally' equivalent for If/Elif statements in Python 'Finally' equivalent for If/Elif statements in Python python python

'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.


Your logic is akin to this:

cleanup = Trueif condition1:    do stuffelif condition2:    do stuffelif condition3:    do stuff....else:    cleanup = Falseif cleanup:    do the cleanup

Ugly, but it is what you asked


you can use try

try:    if-elif-else stufffinally:    cleanup stuff

the exception is raised but the cleanup is done