[Numpy-discussion] Vectorizing a class method

Wojciech Śmigaj puddleglum@o2...
Wed Feb 14 10:10:14 CST 2007


I have a question about the vectorize function. I'd like to use it to 
create a vectorized version of a class method. I've tried the following 

   from numpy import *

   class X:
       def func(self, n):
           return 2 * n  # example
       func = vectorize(func)

Now, when I declare an instance of the class X and invoke func() as an 
unbound method, it works:

   x = X()
   print X.func(x, [1, 2])  # output: [2 4]

But an attempt to invoke it "normally", i.e. like

   print x.func([1, 2])

fails with the message

Traceback (most recent call last):
   File "<stdin>", line 1, in ?
   File "/usr/lib/python2.4/site-packages/numpy/lib/function_base.py", 
line 823, in __call__
     raise ValueError, "mismatch between python function inputs"\
ValueError: mismatch between python function inputs and received arguments

It seems that in this case the class instance (x) isn't passed to the 
vectorize.__call__() method, and as a result the number of arguments 
does not agree with what this method expects.

Does anybody have an idea of how to do it correctly? As a workaround, I 
can write a wrapper function on the module level, which can be 
vectorized without problems, and call it from inside the class---but it 
looks ugly and is tedious given that I have multiple functions to be 
handled in this way.

Thanks in advance for any help,
Wojciech Smigaj

More information about the Numpy-discussion mailing list