
On 10/20/2010 10:35 PM, Nathaniel Smith wrote:
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)
thanks for this probably safer way to do this (I guess safer, as I know nothing about inspect module, but can imagine the value of being explicit as to frames and namespaces)
IMPORTANT USAGE NOTE: never do this :-)
What would you recommand? I do encounter situations where I need instantiation based on the name of the thing to instantiate, typically passed as an argument by the client code/user..... thanks in advance, Johann
-- Nathaniel _______________________________________________ NumPy-Discussion mailing list NumPy-Discussion@scipy.org http://mail.scipy.org/mailman/listinfo/numpy-discussion