Python keyword “finally” trumps “return”

Here is a piece of Python that I did not expect to surprise me:

def a():
        try:
                raise 1
                return 1
        except:
                print "exception!"
                return 2
        finally:
                return 3

print a()

In both Python 2.7 and Python 3, that prints:

exception!
3

It seems that in Python, return is just a casual suggestion to the interpreter, and finally gets to decide, “Nope! Your return is canceled and I will do my return instead!”

Now, to be fair, in Go a defer can change the return value of a function as well. But the defer keyword literally does what it says on the tin, it defers some work until after the return, so you can reason about why it might be changing the return value.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *