I have a number-like class where I have implemented the sqrt, exp, etc. methods so that NumPy functions will broadcast on them when they are in ndarrays.
class A:
def sqrt(self):
return 1.414
This work perfectly in an array of these:
import numpy as np
print(np.sqrt([A(), A()])) # [1.414 1.414]
Obviously, sqrt also works with pure numbers:
print(np.sqrt([4, 9])) # [2. 3.]
However, this does not work when numbers and objects are mixed:
print(np.sqrt([4, A()]))
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-38-0c4201337685> in <module>()
----> 1 print(np.sqrt([4, A()]))
AttributeError: 'int' object has no attribute 'sqrt'
This happens because the dtype of the heterogenous array is object and numpy functions broadcast by calling a method of the same name on each object, but numbers do not have methods with these names.
How do I work around this?
sqrtmethod is caused by theobjectdtype. So all elements of the array have to have method. An object dtype of pure numbers would have the same problem.