Access to return / exception context in finally block

2025-08-30 Thread marius.spix--- via Python-list
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


Re: Python documentary

2025-08-30 Thread Left Right via Python-list
> Had this 'live-test' failed, where would Python be today?

I'm not sure if this is irony or do you honestly believe it
succeeded... but I think that "where Python is today" is pretty
indicative of failure. To me, however, the failure started with the
whole Python 3.X project, Guido being forced into retirement was a
consequence, not the reason for Python's decay.
-- 
https://mail.python.org/mailman3//lists/python-list.python.org