Weird Try-Except-Else-Finally behavior with Return statements
Note that there has been PEP601 to forbid return statements from finally clauses, but it has been rejected. It has however been added to the style guide in PEP8 that it should be avoided.
Because finally
statements are guaranteed to be executed (well, presuming no power outage or anything outside of Python's control). This means that before the function can return, it must run the finally block, which returns a different value.
The Python docs state:
When a return, break or continue statement is executed in the try suite of a try…finally statement, the finally clause is also executed ‘on the way out.’
The return value of a function is determined by the last return statement executed. Since the finally clause always executes, a return statement executed in the finally clause will always be the last one executed:
This means that when you try to return, the finally
block is called, returning it's value, rather than the one that you would have had.
The execution order is:
- try block all completes normally -> finally block -> function ends
- try block run and get into exception A -> finally block -> function ends
- try block make a return value and call return -> finally block -> popup return value -> function ends
So, any return in the finally block will end the steps in advance.