I\'ve found that the numpy.vectorize allows one to convert \'ordinary\' functions which expect a single number as input to a function which can also convert a list of inputs
Remembering a technique I saw in the memoized decorator, I managed to get the decorator to also work for instance methods by subclassing numpy.vectorize as follows:
import numpy as np
import functools
class vectorize(np.vectorize):
def __get__(self, obj, objtype):
return functools.partial(self.__call__, obj)
Now if I decorate the Dummy class' f method with vectorize instead of np.vectorize, the test passes:
class Dummy(object):
def __init__(self, val=1):
self.val = val
@vectorize
def f(self, x):
if x == 0:
return self.val
else:
return 2
def test_3():
assert list(Dummy().f([0, 1, 2])) == [1, 2, 2]
if __name__ == "__main__":
pytest.main([__file__])
with output
test_numpy_vectorize.py .
=========================== 1 passed in 0.01 seconds ===========================
[Finished in 0.7s]