[Tutor] SciPy Optimize-like calling function as string

Peter Otten __peter__ at web.de
Sat Feb 18 19:50:34 EST 2017


Joseph Slater wrote:

> 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:

No, wrap_function wraps an existing function, adds some extra args, and 
provides a way to keep track of the number of invocations. For example:

>>> 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
... 
>>> def demo(*args):
...     print("demo() called with", args)
... 
>>> f = wrap_function(demo, ("one", "two"))
>>> calls, func = wrap_function(demo, ("one", "two"))
>>> calls
[0]
>>> func("x", "y")
<class 'function'>
demo() called with ('x', 'y', 'one', 'two')
>>> calls
[1]
>>> func()
<class 'function'>
demo() called with ('one', 'two')
>>> calls
[2]

To get a function in the current module from its name use globals():

>>> def square(x):
...     return x*x
... 
>>> def twice(x):
...     return 2*x
... 
>>> f = globals()["square"]
>>> f(3)
9
>>> f = globals()["twice"]
>>> f(3)
6

For a function in an external module try getattr():

>>> import os.path
>>> f = getattr(os.path, "join")
>>> f("foo", "bar")
'foo/bar'




More information about the Tutor mailing list