[SciPy-User] How to numpy.vectorize functions with keyword arguments?

nicky van foreest vanforeest at gmail.com
Tue Jun 21 09:28:16 EDT 2011


> Question 2: numpy.vectorized functions don't like being called with keyword
> arguments, the first line in __main__ raises a TypeError.
> Why does this happen? What is the standard method to make vectorized
> functions callable with keyword arguments?

You might try partial functions, see functools.partial in the functools module.

Nicky


>
> I found that writing a wrapper (wrapped_find_x) works, but I'd rather not
> litter my code with many such wrapper functions.
> In the example below it would be ok just using positional arguments, but I
> have many functions, each with ~10 keyword arguments.
>
> Christoph
>
>
> import numpy as np
> @np.vectorize
> def cost(x, scale='square'):
>     """Some complicated function that is supplied by the user"""
>     if scale == 'square':
>         return x ** 2
>     elif scale == 'cube':
>         return x ** 3
>     else:
>         return 0
> @np.vectorize
> def find_x(a, f, scale='square', maxiter=100):
>     """Uses an iterative algorithm to determine a result"""
>     x = 1
>     # just to avoid possibly infinite loop, maxiter should never be reached
>     for _ in range(maxiter):
>         if f(x, scale) > a:
>             break
>         x *= 2
>     return x
> def wrapped_find_x(a, f, scale='square', maxiter=100):
>     return find_x(a, f, scale, maxiter)
> if __name__ == '__main__':
>     print find_x(np.array([10, 100, 1000]), cost, scale='cube') # TypeError
>     print wrapped_find_x(np.array([10, 100, 1000]), cost, scale='cube') # OK
>
> _______________________________________________
> SciPy-User mailing list
> SciPy-User at scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user
>
>



More information about the SciPy-User mailing list