Bug report
Bug description:
>>> i = 1
>>> def a():
... print(i)
...
>>> a()
1
>>> i = 1
>>> def a():
... i = 2
... print(i)
...
>>> a()
2
>>> i = 1
>>> def a():
... i += 1
... print(i)
...
>>> a()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in a
UnboundLocalError: cannot access local variable 'i' where it is not associated with a value
Sorry if this isn't actually a bug, but I can't believe this was intentional...it makes no sense.
CPython versions tested on:
3.11, 3.13
Operating systems tested on:
Windows
Edit:
Okay, so I did some more testing and realized that
i = 1
def a():
i = i + 1
print(i)
also results in this error, but at the i = i + 1
line and not the print(i)
line.
So I guess the problem is just a clash between the local name and the global name.
But it's confusing that when you use +=
it results in the variable no longer being global OR local and gives an error the next time you try to use it..
In my actual use case, it highlighted the variable in a statement unrelated to the assignment like 10 lines down from the assignment.