This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author mscholle
Recipients mscholle
Date 2022-02-02.15:06:10
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1643814371.03.0.343657653727.issue46612@roundup.psfhosted.org>
In-reply-to
Content
Hi, I ran into discussion about scoping in Python (visibility of outer variables in nested functions, global, nonlocal) which made me to create for other some showcases.

I realized there is a space for ambiguity which I extracted to this REPL:

----
>>> x = []
>>> def f(): x += [1]
...
>>> f()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in f
UnboundLocalError: local variable 'x' referenced before assignment
>>> x = []
>>> def f(): x.append(1)
...
>>> f()
>>> x
[1]
----

The documentation says about `x += [1]` it is "translated" to `x.__iadd__([1])`. It would be interesting to know if Python actually documents that `x += [1]` will err with `UnboundLocalError`.

I think there is a natural argument that `x += <rhs>` should behave as an in-place version of `x = x + <rhs>` (where `UnboundLocalError` makes perfect sense), but diving into documentation it seems that `x += <rhs>` should be a syntax sugar for `x.__iadd__(rhs)` in which case `UnboundLocalError` should not happen and looks like some parser artifact.
History
Date User Action Args
2022-02-02 15:06:11mschollesetrecipients: + mscholle
2022-02-02 15:06:11mschollesetmessageid: <1643814371.03.0.343657653727.issue46612@roundup.psfhosted.org>
2022-02-02 15:06:11mschollelinkissue46612 messages
2022-02-02 15:06:10mschollecreate