I was looking at this list of python quirks and was amused that this returns False
:
def t():
try:
return True
finally:
return False
After seeing this I saw the answers here and here which presented the reason why, and that's that the finally
clause will always be executed, no exceptions.
My question is, where is the previous return
value stored:
def t():
try:
return True
finally:
...
Why doesn't this return None
but instead returns the original True
?
And is it possible to access the going to be returned value programatically?
def t():
try:
return True
finally:
...
# if returning != None: return False
I'd like to know if it's possible to do this without using a variable for example:
def t():
retval = None
try:
retval = "Set"
finally:
if retval != None:
return retval
else:
return "Not Set"
and
def t():
retval = None
try:
...
finally:
if retval != None:
return retval
else:
return "Not Set"
return 'Set'
and 'Not Set'
respectively.