calling a function from string

Francesco Guerrieri f.guerrieri at gmail.com
Mon Oct 22 11:41:46 CEST 2007


On 10/22/07, james_027 <cai.haibin at gmail.com> wrote:
> 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?

you could use getattr:

function_name = 'time'  # this is a string
module_name = 'time'   # this is a string, too

my_function = getattr(module_name, function_name) # this is the
function object,
# equivalent to my_function = time.time
my_function() # This is the function call, equivalent to time.time()

bye
francesco



More information about the Python-list mailing list