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. >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. Cheers, Cameron Simpson <c...@cskk.id.au> _______________________________________________ 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/CTCU2D2EAEVCHNNZK2LROZM5J4IW76JF/ Code of Conduct: http://python.org/psf/codeofconduct/