[Numpy-discussion] numpy bug with ndarray subclassing

Dmitrey tmp50@ukr....
Mon Jun 25 06:20:34 CDT 2012




I will use walkaround but I think you'd better fix the numpy bug:

from numpy import ndarray, float64, asanyarray, array
class asdf(ndarray):
__array_priority__ = 10
def __new__(self, vals1, vals2):
obj = asanyarray(vals1).view(self)
obj.vals2 = vals2
return obj
def __add__(self, other):
print('add')
assert not isinstance(other , asdf), 'unimplemented'
return asdf(self.view(ndarray) + other, self.vals2)
def __radd__(self, other):
print('radd')
assert not isinstance(other , asdf), 'unimplemented'
return asdf(self.view(ndarray) + other, self.vals2)

a = asdf(array((1, 2, 3)), array((10, 20, 30)))
z = float64(1.0)

print(a.__array_priority__) # 10
print(z.__array_priority__) # -1000000.0

r2 = a + z
print(r2.vals2) # ok, prints 'add' and (10,20,30)

r1 = z+a
print(r1.vals2)
# doesn't print "radd" (i.e. doesn't enters asdf.__radd__ function at
all)
# raises AttributeError
#"'asdf' object has no attribute 'vals2'"

tried in Python2 + numpy 1.6.1 and Python3 + numpy 1.7.0 dev
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/numpy-discussion/attachments/20120625/8e286b94/attachment.html 


More information about the NumPy-Discussion mailing list