Author martin.panter
Recipients benjamin.peterson, martin.panter, whitequark, yselivanov
Date 2015-05-29.04:01:16
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <>
The first example seems to behave as I would expect. The UnboundLocalError is raised by the print() call, because the “x” variable has been deleted by the exception handler. Equivalent code without using “nonlocal”:

>>> def f():
...     x = None
...     try:
...         raise Exception()
...     except Exception as x:
...         pass
...     print("x", x)  # UnboundLocal due to exception handler
>>> f()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 7, in f
UnboundLocalError: local variable 'x' referenced before assignment

In both cases, I think this is correct behaviour. See <>, which says “When an exception has been assigned using ‘as target’, it is cleared at the end of the except clause.”
Date User Action Args
2015-05-29 04:01:17martin.pantersetrecipients: + martin.panter, benjamin.peterson, yselivanov, whitequark
2015-05-29 04:01:17martin.pantersetmessageid: <>
2015-05-29 04:01:17martin.panterlinkissue24321 messages
2015-05-29 04:01:16martin.pantercreate