Given a string - execute a function by the same name
Robert.Bossy at jouy.inra.fr
Mon Apr 28 12:44:15 EDT 2008
python at bdurham.com wrote:
> I'm parsing a simple file and given a line's keyword, would like to call
> the equivalently named function.
> There are 3 ways I can think to do this (other than a long if/elif
> 1. eval()
> 2. Convert my functions to methods and use getattr( myClass, "method" )
> 3. Place all my functions in dictionary and lookup the function to be
> Any suggestions on the "best" way to do this?
(3) is the securest way since the input file cannot induce unexpected
With this respect (1) is a folly and (2) is a good compromise since you
still can write a condition before passing "method" to getattr(). Btw,
if you look into the guts, you'll realize that (2) is nearly the same as
More information about the Python-list