Let's start off with a question. Given the following code sample:
What do you think the call to foo() will return ?
The correct answer is False.
I encountered this while working on one of my projects, the above control structure caused couple of tests to fail, because I was under the impression that a return statement will return from the function and the finally block won't be executed at all, but that is not how Python works :-) !
What is the problem ?
Fortunately, there is no problem in here, its well-documented.
The Python Official Documentation [1] says,
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.’. A continue statement is illegal in the finally clause. (The reason is a problem with the current implementation — this restriction may be lifted in the future).
So, we now know the reason for this behavior. The finally block is called after we call return in try. Hence, we get the return value of False instead of True.
Bottomline: The finally statement is guaranteed to be executed.
How do we solve this ?
Just use else:
The else block is only executed when we reach the end of the try block.
[1] | http://docs.python.org/2/reference/compound_stmts.html#the-try-statement |