Scope rule pecularities

Peter Otten __peter__ at web.de
Thu May 6 11:36:31 EDT 2004


Antoon Pardon wrote:

> work arounds to make it work. The point is that although a += b
> is supposed to be syntactic sugar for a.__iadd__(b), you need
> a global (and even that won't help if you have nested functions
> and the a is on an intermediate level) to make the first work
> but not for the second.

a += b is not just syntactic sugar for a.__iadd__(b), it also rebinds a:

 >>> class A:
...     def __iadd__(self, other):
...             return "marker"
...
>>> a = A()
>>> a.__iadd__(None)
'marker'
>>> a
<__main__.A instance at 0x4029bbac>
>>> a += None
>>> a
'marker'
>>>

The equivalent a += b would then roughly be a = a.__iadd__(b).

Peter




More information about the Python-list mailing list