"eval vs operator.methodcaller" - which is better?

Laxmikant Chitare laxmikant.general at gmail.com
Mon Mar 18 09:30:15 EDT 2013


Hi,

I have a program that picks module and method name from a
configuration file and executes the method. I have found two ways to
achieve this.

Apporach 1:
---------------------------
moduleName = 'mymodule'    #These two variables are read from conf file.
methodName = 'mymethod'

import operator
myModule = __import__('mymodule')
myMethod = operator.methodcaller('mymethod')
val = myMethod(myModule)
print val
---------------------------

Apporach 2:
---------------------------
moduleName = 'mymodule'    #These two variables are read from conf file.
methodName = 'mymethod'

val = eval('myModule.' + methodName + '()')
print val
---------------------------

Question: Which approach is better and why. Is there any other better
way to do this?

Regards,
Laxmikant



More information about the Python-list mailing list