Cumulative assignment statement
The cumulative assignment statement is a combination of binary operations and assignment statements into a single statement.
>>> a = 1
>>> a = a + 1
>>> a
2
>>> a = 1
>>> def f():
... b = a + 1
... return b
...
>>> f()
2
>>> a = 1
>>> def f():
... a = a + 1
... return a
...
>>> f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in f
UnboundLocalError: local variable 'a' referenced before assignment
>>> a = 1
>>> def f():
... global a
... a = a + 1
... return a
...
>>> f()
2
Why do I get an UnboundLocalError when a variable has a value?
According to it, it seems to be explained like this.
This is because when you assign to a variable within a scope, that variable becomes local to that scope, hiding variables of the same name in the outer scope.
Thanks to @gotta_dive_into_python
I'm experimenting that "when assigning to a variable in a certain scope, that variable becomes local to that scope" is the same as being registered in locals ()
. There is another mystery in my house.
>>> def f():
... a = locals()
... return a
...
>>> f()
{}
>>> def f():
... a = locals()
... b = 1
... return a
...
>>> f()
{}
>>> def f():
... a = locals()
... b = locals()
... return a
...
>>> f()
{'a': {...}}
Recommended Posts