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
How is this better than
def f(x):
try:
quot = 10 / x
except ZeroDivisionError as exc:
log_error(exc)
return 0
else:
log_return(quot)
return quot + 1
finally:
"Any cleanup processing needed before returning"
or
def f(x):
try:
quot = 10 / x
except ZeroDivisionError as exc:
log_error(exc)
res = 0
else:
log_return(quot)
res = quot + 1
finally:
return res
Best wishes
Rob Cliffe
--
https://mail.python.org/mailman3//lists/python-list.python.org