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


Groups > comp.lang.python > #41417 > unrolled thread

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

Started byJean-Michel Pichavant <jeanmichel@sequans.com>
First post2013-03-18 14:58 +0100
Last post2013-03-18 14:58 +0100
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python


Contents

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

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

FromJean-Michel Pichavant <jeanmichel@sequans.com>
Date2013-03-18 14:58 +0100
SubjectRe: "eval vs operator.methodcaller" - which is better?
Message-ID<mailman.3446.1363615133.2939.python-list@python.org>
----- 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.

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web