[Numpy-discussion] strange behavior of += with object array

Neal Becker ndbecker2 at gmail.com
Fri Nov 1 06:37:18 EDT 2013


Robert Kern wrote:

> On Thu, Oct 31, 2013 at 11:22 PM, Neal Becker <ndbecker2 at gmail.com> wrote:
>>
>> import numpy as np
>> #from accumulator import stat2nd_double
>>
>> ## Just to make this really clear, I'm making a dummy
>> ## class here that overloads +=
>> class stat2nd_double (object):
>>     def __iadd__ (self, x):
>>         return self
>>
>> m = np.empty ((2,3), dtype=object)
>> m[:,:] = stat2nd_double()
>>
>> m[0,0] += 1.0  <<<< no error here
>>
>> m += np.ones ((2,3)) <<< but this gives an error
>>
>> Traceback (most recent call last):
>>   File "test_stat.py", line 13, in <module>
>>     m += np.ones ((2,3))
>> TypeError: unsupported operand type(s) for +: 'stat2nd_double' and 'float'
> 
> Yeah, numpy doesn't pass down the __iadd__() to the underlying objects.
> object arrays are the only dtype that could implement __iadd__() at that
> level, so it has never been an operation added to the generic "numeric ops"
> system. Look in numpy/core/src/multiarray/numeric.c for more details. It
> might be possible to implement a special case for object arrays in
> array_inplace_add() and the rest.
> 
> --
> Robert Kern

What is a suggested workaround?

The best I could think of is:
np.vectorize (lambda s,x: s.__iadd__(x)) (m, np.ones ((2,3)))

where m is my matrix of objects and np.ones ((2,3)) is the array to += each
element.






More information about the NumPy-Discussion mailing list