+ 3
Why print 2?
def Func(): try: return 1 finally: return 2 print(Func()) why print only 2 without 1? https://code.sololearn.com/caiY9jxVnPE0/?ref=app
4 Respostas
+ 5
From the github source documentation for the try statement itself:
https://github.com/JUMP_LINK__&&__python__&&__JUMP_LINK/cpython/blob/master/Doc/reference/compound_stmts.rst#id120
"[When return, break or continue appear in try, finally is also executed on the way out] ... The return value of a function is determined by the last :keyword:`return` statement executed. Since the :keyword:`finally` clause always executes, a :keyword:`return` statement executed in the :keyword:`finally` clause will always be the last one executed:
def foo():
try:
return 'try'
finally:
return 'finally'
foo()
'finally' "
+ 12
"Because finally statements are guaranteed to be executed (well, presuming no power outage or anything outside of Python's control). This means that before the function can return, it must run the finally block, which returns a different value.
The Python docs state:
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.’ A continue statement is illegal in the finally clause. (The reason is a problem with the current implementation — this restriction may be lifted in the future).
This means that when you try to return, the finallyblock is called, returning it's value, rather than the one that you would have had."
From https://stackoverflow.com/questions/11164144/weird-try-except-else-finally-behavior-with-return-statements
+ 4
Александр Лебедев Please don't worry about this answer (to avoid confusing you). I'm just adding some [meta information].
David Ashton I decompiled this at first; if you follow the opcode list (copy the code into the multiline string then select code 4):
https://code.sololearn.com/cxYMW29npKWp/?ref=app
... it implies Python completely ignores the first return, but I understand it executes.
A real debugger would help because on a bad return (like return UndefinedVar) an exception is thrown...so it's almost like Python "tries" the first return to see if it would be successful but leaves the result on the execution stack, where it's optionally overwritten -- kindof like hitting the sequence point in c/c++ but more reliable. This makes me wonder about edge-case behavior in the gap :)
Anyway, not to distract or go offtopic, I just thought this was curious.
+ 3
thank you!