Scope rule pecularities

Antoon Pardon apardon at forel.vub.ac.be
Fri May 7 03:12:35 EDT 2004


Op 2004-05-06, Peter Otten schreef <__peter__ at web.de>:
> 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).

Well I would say that seems to go against the intention as stated
in the reference manual. += and associated should attempt the
operation in place. If you do an operation in place there is
no need to rebind the variable.

-- 
Antoon Pardon



More information about the Python-list mailing list