10

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

2

3 Answers 3

10

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

0
1

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. :)

0

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? ;)

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.