programmatically calling a function

Reinhold Birkenfeld reinhold-birkenfeld-nospam at wolke7.net
Sat Mar 5 13:12:53 EST 2005


Doug Schwarz wrote:

>> > Dave,
>> > 
>> > I think eval might be what you're looking for:
>> > 
>> > f = eval('len')
>> > length = f([1,2,3])
>> 
>> But only if the string given to eval is checked thorougly for allowed
>> contents. Better use getattr.
> 
> Actually, upon reading Peter Hansen's reply more carefully, I wil defer 
> to his approach, namely,
> 
> def foo():
>     print "foo"
> 
> f = globals()["foo"]
> 
> as I suspect that it will be more efficient.  You still need to make
> sure that the string in question is one of the keys in the globals() 
> dictionary or else handle the error -- just as with eval.

Well, with eval, you need to really check the string before calling
eval, with globals() you just need to catch an KeyError, which is cheaper.

> I don't see how getattr solves the original problem.  What, exactly, is 
> the first argument to getattr?

If run at the toplevel, __main__. If the functions are in a module, this
module. But you are right, globals() is more understandable.

However, if the use case is as in the OP's example, Peter Hansen's first
approach is surely the fastest and most concise.


Reinhold



More information about the Python-list mailing list