tags:

views:

134

answers:

3

I found this interesting item in a blog today:

def abc():
    try:
        return True
    finally:
        return False

print "abc() is", abc()

Can anyone tell why it does what it does?

Thanks, KR

+8  A: 

If the finally block contains a return or break statement the result from the try block is discarded

it's explained in detail in the python docu

Nikolaus Gradwohl
aww you beat me :)
townsean
+1  A: 

Go to the try statement area:

http://docs.python.org/reference/compound_stmts.html

The finally statement is still executed. Really interesting situation though. I learned something new. :)

townsean
A: 

Thanks for pointer to the docs. I could not get past the 'return True' to even think of looking there.

Part of the documentation reads:

If finally is present, it specifies a ‘cleanup’ handler. The try clause is executed,...

which suggests that the return True is executed. However, this is later clarified:

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

Which explains the observed behavior.

What kind of mind would think up some code like this in the first place? ;)

OddZon