calling a function from string
Bruno Desthuilliers
bruno.42.desthuilliers at wtf.websiteburo.oops.com
Mon Oct 22 08:03:21 EDT 2007
Jarek Zgoda a écrit :
> Trent Nelson napisał(a):
>>> 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?
>> Use 'eval' in one of the following fashions:
>>
>> a_string_1 = 'datetime.' + 'today'
>> a_string_2 = 'datetime.' + 'today()'
>>
>> eval(a_string_1)()
>> eval(a_string_2)
>
> Do not use eval(). Not only it's deprecated,
Chapter and verse ???
> it's also unsafe.
it's *potentially* unsafe. As long as the eval'd code comes from a
trusted source, there should be no security problem.
I agree that eval is usually not the solution, but mainly because Python
has far better (wrt/ readability and maintainance) options for this kind
of things.
More information about the Python-list
mailing list