Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #41417

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

Date 2013-03-18 14:58 +0100
From Jean-Michel Pichavant <jeanmichel@sequans.com>
Subject Re: "eval vs operator.methodcaller" - which is better?
Newsgroups comp.lang.python
Message-ID <mailman.3446.1363615133.2939.python-list@python.org> (permalink)

Show all headers | View raw


----- 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.

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: "eval vs operator.methodcaller" - which is better? Jean-Michel Pichavant <jeanmichel@sequans.com> - 2013-03-18 14:58 +0100

csiph-web