On 17/11/2020 10:22 am, Cameron Simpson wrote:
On 17Nov2020 09:55, Mark Shannon <m...@hotpy.org> wrote:
I'm wondering why
```
x = "value"
try:
1/0
except Exception as x:
pass
```
does not restore "value" to x after
the `except` block.
Because the except is not a new scope. So it is the same "x".
Here:
https://docs.python.org/3/reference/compound_stmts.html#try
it says:
When an exception has been assigned using as target, it is cleared
at the end of the except clause. This is as if
except E as N:
foo
was translated to
except E as N:
try:
foo
finally:
del N
This means the exception must be assigned to a different name to be
able to refer to it after the except clause. Exceptions are cleared
because with the traceback attached to them, they form a reference
cycle with the stack frame, keeping all locals in that frame alive
until the next garbage collection occurs.
Sorry, I should have made it clearer.
I'm not asking what are the semantics of the current version of Python.
I'm asking why they are that way.
Here's an example of restoring the value of the variable after the
`except` block:
def f(x):
... try:
... 1/0
... except Exception as x:
... pass
... return x
...
f("hi")
'hi'
In the Python 3.8.5 I don't see this:
Python 3.8.5 (default, Jul 21 2020, 10:48:26)
[Clang 11.0.3 (clang-1103.0.32.62)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def f(x):
... try:
... 1/0
... except Exception as x:
... pass
... return x
...
>>> f(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 6, in f
UnboundLocalError: local variable 'x' referenced before assignment
and the same outside a function.
But why have we chosen for it do this?
Wouldn't restoring the value of x be a superior option?
Cheers,
Mark.
_______________________________________________
Python-Dev mailing list -- python-dev@python.org
To unsubscribe send an email to python-dev-le...@python.org
https://mail.python.org/mailman3/lists/python-dev.python.org/
Message archived at
https://mail.python.org/archives/list/python-dev@python.org/message/3JMEHLXJ7ZF2FN5ZFUIDMZHODNJYTE6A/
Code of Conduct: http://python.org/psf/codeofconduct/