[Numpy-discussion] inplace add

Tim Hochberg tim.hochberg at cox.net
Tue Mar 28 12:18:04 EST 2006


Travis recently brought up the odd behaviour of adding an array to a 
list using inplace add, notably:

     >>> l = range(4)
     >>> a = arange(4)
     >>> l += a
     >>> l
    array([0, 2, 4, 6])

It was agreed that this was a deficiency in PyNumber_InplaceAdd and this 
is slated to be fixed. Hopefully for 2.5. Thanks Travis, Robert Kern and 
Armin Rigo for taking care of this.

I had planned to write something here about, how, although this fixes 
the problem with lists, there is a similar problem with tuples, and 
since tuples don't have __iadd__, we could still expect to see this 
problem there. However, I now think that's not the case. The proposed 
resolution order will work something like:

        def iadd(a, b):
            if hasattr(a, '__iadd__'):
               tmp = a.__iadd__(b)
               if tmp is not NotImplemented:
                   return tmp
            if hasattr(a, '__add__'):
                tmp = a.__add__(b)
                if tmp is not NotImplemented:
                    return tmp
            if hasattr(b, '__radd__'):
                temp = b.__radd__
                if tmp is not NotImplemented:
                    return tmp
            raise TypeError("can't add %r and %r" % (type(a), type(b)))

You'll notice if you try this, that "iadd(atuple, anarray)" throws an 
error because atuple refuses to be added to anything other than another 
tuple.That raises an error at "__add__" and prevents any oddities.  So, 
we should be safe from both tuples and lists, and really they are the 
only types that are prevalent enough to worry about in this context.

Still, I have a niggling feeling that iadd should really not be calling 
radd at all, but nothing concrete.

-tim





More information about the NumPy-Discussion mailing list