programmatically calling a function

Doug Schwarz see at sig.for.address.edu
Sat Mar 5 12:18:55 EST 2005


In article <38tuhpF5qv9s2U1 at individual.net>,
 Reinhold Birkenfeld <reinhold-birkenfeld-nospam at wolke7.net> wrote:

> 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.
> 
> Reinhold


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.

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

-- 
Doug Schwarz
dmschwarz&urgrad,rochester,edu
Make obvious changes to get real email address.



More information about the Python-list mailing list