Message412365
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. |
|
Date |
User |
Action |
Args |
2022-02-02 15:06:11 | mscholle | set | recipients:
+ mscholle |
2022-02-02 15:06:11 | mscholle | set | messageid: <1643814371.03.0.343657653727.issue46612@roundup.psfhosted.org> |
2022-02-02 15:06:11 | mscholle | link | issue46612 messages |
2022-02-02 15:06:10 | mscholle | create | |
|