I'm trying to use the scipy.optimize code as an example to be able to avoid 
using *eval* to call a function named by a string. 

The following appears to be the code used to do this:
# from scipy optimize
> def wrap_function(function, args):
>     ncalls = [0]
>     if function is None:
>         return ncalls, None
> 
>     def function_wrapper(*wrapper_args):
>         ncalls[0] += 1
>         print(type(function))
>         return function(*(wrapper_args + args))
> 
>     return ncalls, function_wrapper


where I should be able to use it to make the following work:

> def sqr(x):
>     return x**2.
> 
> 
> func = 'sqr'
> 
> args=()
> fcalls, func = wrap_function(func, args)
> 
> x=3
> func(x)

where I get:

> <class 'str'>
> 
> ---------------------------------------------------------------------------
> TypeError
>                                  Traceback (most recent call last)
> 
> <ipython-input-32-832f2a14d895> in <module>()
>       7 
>       8 x=3
> ----> 9 func(x)
> 
> 
> 
> <ipython-input-19-6f99e62c64af> in function_wrapper(*wrapper_args)
>       8         ncalls[0] += 1
>       9         print(type(function))
> ---> 10         return function(*(wrapper_args + args))
>      11 
>      12     return ncalls, function_wrapper
> 
> 
> 
> TypeError: 'str' object is not callable


This works in *optimize* but not for me. What am I missing?

I've seen this done with dictionaries on some pages, but it seems that this is 
intended to be faster (which will become necessary for me in the future). 

Thanks,
Joe




_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to