syntax glitch with +=
Denis S. Otkidach
ods at strana.ru
Fri Feb 21 10:12:36 EST 2003
On Thu, 20 Feb 2003, Jp Calderone wrote:
JC> Not if you use a global declaration (or if you don't,
JC> since an exception
JC> is raised and the assignment never occurs ;)
You are not right, it changes value in-place (if possible) _and_
assign it to the same variable.
x += y <=> x = x.__iadd__(y)
>>> def add(v):
... l += [v]
...
>>> l = []
>>> add(1)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 2, in add
UnboundLocalError: local variable 'l' referenced before
assignment
But this works:
>>> def add(v):
... local_l = l
... local_l += [v]
...
>>> add(2)
>>> l
[2]
and even with nested scopes:
>>> def f():
... l = []
... def add(v):
... local_l = l
... local_l += [v]
... add(3)
... print l
...
>>> f()
[3]
--
Denis S. Otkidach
http://www.python.ru/ [ru]
More information about the Python-list
mailing list