Python keyword “finally” trumps “return”

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

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

print a()

In both Python 2.7 and Python 3, that prints:


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.


Leave a Reply

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