calling a function from string

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Mon Oct 22 08:00:02 EDT 2007


james_027 a écrit :
> hi,
> 
> i have a function that I could like to call, but to make it more
> dynamic I am constructing a string first that could equivalent to the
> name of the function I wish to call. how could I do that? the string
> could might include name of the module.
> 
> for example
> 
> a_string = 'datetime.' + 'today()'
> 
> how could I call a_string as function?

The obvious answer is to use eval or exec, but it's 99.99 times out of 
100 the wrong solution.

Better solutions usually rely on Python's introspection features - 
mostly globals(), locals(), sys.modules, and of course getattr().



More information about the Python-list mailing list