
On Tue, Nov 17, 2020 at 3:57 AM Mark Shannon <mark@hotpy.org> wrote:
On 17/11/2020 10:22 am, Cameron Simpson wrote:
On 17Nov2020 09:55, Mark Shannon <mark@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?
Because that solution didn't occur to anyone at the time? Because we didn't realize anyone would want those semantics? Because the current semantics evolved from previous semantics that didn't erase the variable at the end of the except block? Why do you need this question answered?
Wouldn't restoring the value of x be a superior option?
That depends. It would be more work to implement, which (at the time that feature was designed, probably more so than today) was a concern. But "superior" is rather subjective. -- --Guido van Rossum (python.org/~guido) *Pronouns: he/him **(why is my pronoun here?)* <http://feministing.com/2015/02/03/how-using-they-as-a-singular-pronoun-can-c...>