[Numpy-discussion] function name as parameter

Nathaniel Smith njs@pobox....
Wed Oct 20 15:35:49 CDT 2010


On Wed, Oct 20, 2010 at 6:51 AM, Johann Cohen-Tanugi
<cohen@lpta.in2p3.fr> wrote:
> If you really need to pass the function name :
> In [3]: def my_func(x):
>    ...:     return 2*x
>
> In [4]: def caller(fname,x):
>    ...:     return eval("%s(%f)"%(fname,x))
>
> In [5]: caller("my_func",2)
> Out[5]: 4.0

The better way to do this is:

import inspect
def call_this(fname, x):
  caller_frame = inspect.currentframe().f_back
  f = caller_frame.f_locals.get(fname, caller_frame.f_globals.get(fname))
  return f(x)

IMPORTANT USAGE NOTE: never do this :-)

-- Nathaniel


More information about the NumPy-Discussion mailing list