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 30/08/2025 12:03, marius.spix--- via Python-list wrote: > Dear mailing list, > > there is currently no direct way to observe the current interpreter state in a finally block without tracing. > > My idea is introducing an immutable __exit_context__ magic variable, which would have one of three possible values: > > * ReturnContext(value), if a return statement is about to exit the try, except or else block > * ExceptionContext(exc, tb, caught: bool), if an exception has occured in the try, except or else block > * None, if the try block completes normally without return or exception > > This variable would allow to inspect the cause, why a try block is left and make post-processing easier without using workarounds like storing the exception in a temporary variable. > > sys.exc_info() is not always useful, because it always returns (None, None, None) when the exception has been caught in the except block. > > This is an example, how __exit_context__ could be used: > > def f(x): > try: > return 10 / x > except ZeroDivisionError: > pass > finally: > if isinstance(__exit_context__, ExceptionContext): > log_error(__exit_context__.exc) > return 0 > elif isinstance(__exit_context__, ReturnContext): > log_return(__exit_context__.value) > return __exit_context__.value + 1 > > I wonder if it would be a candidate for a PEP to be implemented in the Python standard. > > Best regards > > Marius Spix 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 -- https://mail.python.org/mailman3//lists/python-list.python.org