[Python-ideas] Allow accessing return value inside finally clause
Georg Brandl
g.brandl at gmx.net
Tue Dec 25 22:55:41 CET 2012
On 12/25/2012 10:46 PM, Ram Rachum wrote:
> Say I have this function:
>
> def f():
> try:
> return whatever()
> finally:
> pass # I want to get what `whatever()` returned in here
>
> I want to get the return value from inside the `finally` clause.
>
> I understand that this is currently not possible. I'd like that to be possible
> because that would allow post-processing of a function's return value.
>
> What do you think?
Please supply a more complete example of what you are trying to achieve.
As it is, I wonder what your motivation is for using a "finally", because
in the case of an exception, there won't even *be* a return value to
postprocess.
If you're trying to use try-finally as a sort of nonlocal exit mechanism (like
the famous "goto done" in CPython sources), you probably would be fine with
ret = None
try:
if x:
ret = blah
return
# more cases with returns here
finally:
# post-process ret here
return ret
But I would consider this an abuse of try-finally, especially since it
suppresses proper propagation of exceptions.
cheers,
Georg
More information about the Python-ideas
mailing list