I was going through the python docs to improve my core python and I was reading about errors and exceptions
In the doc it says
If a finally clause includes a return statement, the finally clause’s return statement will execute before, and instead of, the return statement in a try clause.
It also provides this example below:
def bool_return():
try:
return True
finally:
return False
bool_return()
Now looking at this example the above statement seems straight and fair enough, but if you modify that example a bit to make it look like this:
def bool_return():
try:
return print("foo")
finally:
return False
bool_return()
Now, if you run this you will see that foo
will be printed and False will be returned. Now the doc says that finally clause's return will execute before, and instead of, try clause's return statement. If so, then why I can see the foo being printed?
I debugged this snippet with pycharm and it shows that the try clause's return statement is executed first and the string is printed and then it's output which is None
is returned due to return
statement, and the return statement in the finally clause will be executed later, which is the last return of the program so the function overrides previous return and False
is returned.
My question is:
1) Why does doc say finally clause's return statement is executed before?
2) Why does doc say finally clause's return statement is executed instead of try clause's return statement?
I believe both the statements are the opposite of what happens in reality.
EDIT:
After reading @iBug's answer it is clear now that how the print("foo")
is evaluated but None
is not returned. Basically, the expression is evaluated first and then return
happens. Later on return False
in finally is executed. Which makes clear why we get the output that we did.
Still, I see that the return False
in finally is executed after the return print("foo")
of try.
Or as per @iBug's comment, 10 RETURN_VALUE
is completely bypassed?
EDIT
This is now resolved in the documentation and it is correct now on what will be returned. However, if you wish to know "how" then read all the comments and answer carefully.
return print("foo")
is actually 2 separate steps, first the print function is called, then the return valueNone
is assigned to the return statement - then the finally blocks return statement overrides the previous statements value. This is a bit over simplified but you get what I meanprint
, load"foo"
, call function, return value, for starters), but all those steps are part of executing thereturn
statement. Return value computation is separate from actually returning the value, but it isn't separate from the overallreturn
statement.