var or inout parm?

Hrvoje Niksic hniksic at xemacs.org
Fri Dec 12 09:51:31 EST 2008


sturlamolden <sturlamolden at yahoo.no> writes:

> On Dec 12, 3:08 pm, Marc 'BlackJack' Rintsch <bj_... at gmx.net> wrote:
>
>> No bug because a mutation *is* attempted.  ``a += x`` calls `a.__iadd__`
>> which *always* returns the result which is *always* rebound to the name
>> `a`.  Even with mutable objects where `__iadd__()` simply returns
>> `self`!
>
> No, a mutation is not attempted, even if __iadd__() always returns a
> value.

Mutation is attempted.  A += x (where "A" could be anything valid at
the left-hand side of assignment, including item subscript) is not
implemented intuitivaly, as:

if hasattr(b, '__iadd__'):
    A.__iadd__(x)   # ignore return value
else:
    A = A.__add__(x)

It is implemented as something like:

if hasattr(b, '__iadd__'):
    newval = A.__iadd__(x)
else:
    newval = A.__add__(x)
A = newval

So the only difference between __add__ and __iadd__ is that __iadd__
is only consulted on +=, where as __add__ is consulted on both + and
+= (in the latter case only if __iadd__ is missing).

> The tuple should check that it is
> actually being *mutated* before it raises any exception.

Tuple has no way to check that.  What tuple sees is only the last
line:

t[0] = newval

At that point, the information about what is really going on is long
lost.  The only thing tuple could do is detect that the same object is
being written that's already there, but tuple doesn't do that by
design.



More information about the Python-list mailing list