[Numpy-discussion] function name as parameter

Nathaniel Smith njs@pobox....
Wed Oct 20 16:17:26 CDT 2010


On Wed, Oct 20, 2010 at 1:58 PM, Johann Cohen-Tanugi
<cohen@lpta.in2p3.fr> wrote:
> On 10/20/2010 10:35 PM, Nathaniel Smith wrote:
>> 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)

Right, there are two big advantages: (1) it looks up the name in the
*caller*'s namespace, so it works even if the function is called from
another module, (2) you don't have to rely on 'x' going
float->string->back to float. (Which probably doesn't make much
difference if you just have a single float argument, but for anything
more complicated you can avoid a lot of hassle.)

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

Really, the recommendation is to define your API differently, so that
people pass in actual objects (or whatever makes sense) instead of
strings. But if you need to do this ugly thing for some reason (I've
only needed it once, in a *very* exotic situation way outside what any
normal scientific programmer would run into), then 'inspect' is
probably the best way to accomplish it.

-- Nathaniel


More information about the NumPy-Discussion mailing list