Re: Access to return / exception context in finally block

Rob Cliffe via Python-list <[email protected]>
Newsgroups gmane.comp.python.general
Message-ID <[email protected]>

On 01/09/2025 14:26, marius.spix--- via Python-list wrote:
>> In your example when would isinstance(__exit_context__, ReturnContext)
>> be True and when would it be False? What would __exit_context__.value
>> be? I can't think of a sensible meaning for it. If no exception occurs,
>> is the value returned by f supposed to be 10/x or __exit_context__.value
>> + 1 # whatever that is
>> Best wishes
>> Rob Cliffe
> Dear Rob,
>
> isinstance(__exit_context__, ReturnContext) would only be True, when the try, except or else block is left using a return statement.
>
> __exit_context__.value  would be the return value of f(x), in that case 10/x. Currently it is not possible to access this value in the finally block, but it can be overwritten, as the return statement is compiled into a new RETURN_VALUE opcode.
>
> In this example, f(x) would return 10/x + 1 if x != 0 else 0.
>
> I think that this magic variable would make error handling much more easier. What do you think?
>
> Best wishes
>
> Marius Spix
Sorry, but it looks really confusing to have a statement
return 10 / x which does not (let us say) raise an exception, yet does 
not represent the actual value returned by the function. Sure, you can 
already do this: def f(x): try: return 1 # Does not return except 
Exception: pass finally: return 2 # Actually returns 2 but it is IMO 
emphatically not something that should be encouraged. Best wishes Rob 
Cliffe
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.