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
-- 
https://mail.python.org/mailman3//lists/python-list.python.org

Reply via email to