I have a return statement inside a try
clause:
def f():
try:
return whatever()
finally:
pass # How do I get what `whatever()` returned in here?
Is it possible to get the return value inside the finally
clause?
This is more of a theoretical question, so I'm not looking for a workaround like saving it to a variable.
A finally block is always run, so the last thing to be returned in the function is whatever is returned in the finally block.
When an exception occurs, both finally and except blocks execute before return . Otherwise only finally executes and else doesn't because the function has already returned. Show activity on this post. The else block isn't executed because you have left the function before it got a chance to do so.
Since return_42() returns a numeric value, you can use that value in a math expression or any other kind of expression in which the value has a logical or coherent meaning. This is how a caller code can take advantage of a function's return value.
You can avoid unintentionally raising an error using the dictionary's built in get function. Get will return None if the value at the specified key does not exist instead of throwing an exception.
No, it isn't - the finally
clause's content is independent from return mechanics; if you do want to see what value is returned you'd have to do as you mentioned and explicitly save it somewhere that's in-scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With