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

Jean-Michel Pichavant jeanmichel at sequans.com
Mon Mar 18 14:58:44 CET 2013


----- Original Message -----
> 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
> --
> http://mail.python.org/mailman/listinfo/python-list
> 

Hi,

Any alternative to eval is always better than eval (aka eval is evil). 
Your code is not working in my python 2.5 env (operator has no methodcaller).

try something like

moduleName = 'mymodule'    #These two variables are read from conf file.
methodName = 'mymethod'
myModule = __import__(moduleName)
myFunc = getattr(myModule, methodName)
myFunc()


JM


-- IMPORTANT NOTICE: 

The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you.


More information about the Python-list mailing list