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

Tim McNamara
  • 18,019
  • 4
  • 52
  • 83
OddZon
  • 133
  • 7
  • Although not entirely the same, a good discussion of this can be found here: http://stackoverflow.com/questions/1611561/python-error-handling-with-try-finally – dave Aug 02 '10 at 17:47
  • -1: did not even try to look up the finally statement in http://docs.python.org/reference/compound_stmts.html#the-try-statement – S.Lott Aug 02 '10 at 18:51

3 Answers3

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

Nikolaus Gradwohl
  • 19,708
  • 3
  • 45
  • 61
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. :)

Ashley Grenon
  • 9,305
  • 4
  • 41
  • 54
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? ;)

OddZon
  • 133
  • 7