Given a string - execute a function by the same name
mccredie at gmail.com
Mon Apr 28 18:49:26 CEST 2008
On Apr 28, 9:33 am, pyt... 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?
> Thank you,
You can always import yourself and use getattr on that module.
in file "mytest.py":
print "foo called"
def call_by_name(name, *args, **kwargs):
f = getattr(mytest, "foo")
if __name__ == "__main__":
Alternatively you can import __main__ if you are always going to be
running directly from that file.
More information about the Python-list