[SciPy-User] How to numpy.vectorize functions with keyword arguments?
Christoph Deil
Deil.Christoph at googlemail.com
Wed Jun 22 04:41:31 EDT 2011
On Jun 21, 2011, at 3:28 PM, nicky van foreest wrote:
>> 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 tried using functools.partial but couldn't make it work.
Can you give an example of how to use it to make a vectorized function accept keyword arguments?
E.g. the following lines still give the same TypeError as before:
a = np.array([10, 100, 1000])
cube_find_x = ft.partial(find_x, scale='cube')
print cube_find_x(a, cost)
Also this is not really what I want, which is to make find_x accept keyword arguments without writing the wrapper myself,
maybe there is a way to write a decorator handle_kwargs so that I can simply write something like the following code?
@handle_kwargs
@np.vectorize
def find_x(...)
....
>
>
>>
>> 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
>>
>>
> _______________________________________________
> SciPy-User mailing list
> SciPy-User at scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.scipy.org/pipermail/scipy-user/attachments/20110622/39a9b11c/attachment.html>
More information about the SciPy-User
mailing list