I'm trying to use the __numpy_ufunc__()
method explained here in the Numpy v1.11 docs, to override the behavior of numpy ufuncs on a subclass of ndarray
, but it never seems to get called. Despite this use case being listed in the guide, I can't find any examples of anyone actually using __numpy_ufunc__()
. Has anyone tried this? Here's a minimal example:
# Check python version
import sys
print(sys.version)
3.5.1 |Continuum Analytics, Inc.| (default, Jun 15 2016, 15:32:45)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)
# Check numpy version
import numpy as np
print(np.__version__)
1.11.2
# Subclass ndarray as discussed in
# https://docs.scipy.org/doc/numpy/user/basics.subclassing.html
class Function(np.ndarray):
# Create subclass object by view
def __new__(cls):
obj = np.asarray([1,2,3]).view(cls)
return obj
# I'm not even adding anything functionality yet
def __array_finalize(self,obj): pass
# Override ufuncs
def __numpy_ufunc__(ufunc, method, i, inputs, **kwargs):
print("In PF __numpy_ufunc__")
# do other stuff here if I want to
# and probably need to return a value...
# Create two Functions
f1=Function()
f2=Function()
# Check that they are correctly initialized as Function objects
# not just ndarrays
print(type(f1),type(f2))
⟨class 'main.Function'⟩ ⟨class 'main.Function'⟩
# Add using operator
f1+f2
Function([2, 4, 6])
# Add, explicitly demanding a numpy ufunc
np.add(f1,f2)
Function([2, 4, 6])
Clearly, the subclassing works, and it's using numpy to add arrays behind the scenes. I'm using a new enough version of numpy to employ the __numpy_ufunc__()
feature (according to that docs page, it's new in v1.11). But this code never prints out "In PF __numpy_ufunc__"
. What gives?
This functionality has finally been released in Numpy 1.13 under a new name:
This should resolve this issue.