+ 4
Can you please explain the output of this code?
def foo(): try: return 1 finally: return 2 k = foo() print(k) Answer is 2
6 Answers
+ 2
according to https://docs.python.org/3/tutorial/errors.html#defining-clean-up-actions :
If the try statement reaches a break, continue or return statement, the finally clause will execute just prior to the break, continue or return statementâs execution.
If a finally clause includes a return statement, the returned value will be the one from the finally clauseâs return statement, not the value from the try clauseâs return statement.
+ 4
Ipang and andriy kan, I know that the code under finally block will always run. My answer was 1 and 2. Why 1 didn't run?
+ 4
Ah ok, I get it finally :)
+ 2
From the Python lesson:
"Code within a finally statement always runs after execution of the code in the try, and possibly in the except, blocks."
Whether or not an exception happened, `finally` block will be executed. Although, I also find this to be a bit odd, because as per my understanding - return statement will return the control flow to the function caller.
https://www.sololearn.com/learn/Python/2442/
+ 1
All JUMP_LINK__&&__Python__&&__JUMP_LINK Challenges are welcomed đ€
Answer is in the docs linked with Andiy Kan's previous answer
+ 1
All Python Challenges are welcomed đ€ ,
According to the documentation https://docs.python.org/3/tutorial/errors.html#defining-clean-up-actions :
the returned value will be the one from the finally clauseâs return statement,
not the value from the try clauseâs return statement.
I think, that is because return 1 in the try block can't be executed before finally block, since finally statements are guaranteed to be executed.
I don't know how well you know as low-level code is executed, but try to explain:
As I understand, when Python translates source code to low-level code, it replaces return statement in try block with jump instruction that jumps to code of finally block (as it can't return from try). return instruction itself is put after finally block. It will be executed after finally block code complete execution.
But when return statement is in finally block it is translated just to return instruction (of course with additional instructions necessary to clean up stack and return the result). When that return instruction is executed, a return from the function occurs, so the return instruction that was put after fnally block is not executed.
As a result, the return value of a function is determined by the return statement which was executed last. The last executed return statement in your code is return 2.