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

Laxmikant Chitare laxmikant.general at gmail.com
Mon Mar 18 10:36:26 EDT 2013


Thank you Chris, Michel and Steven for your feedback.

Steven, yes I realised that the examples are faulty. I intended to use
variables instead of string literals. I will be careful next time.

On 3/18/13, Steven D'Aprano <steve+comp.lang.python at pearwood.info> wrote:
> On Mon, 18 Mar 2013 19:00:15 +0530, Laxmikant Chitare wrote:
>
>> 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
>
> Since your example code only uses string literals, the best way to write
> this would be:
>
> import mymodule
> mymodule.mymethod()
>
> But I expect that your example was faulty, and you intended to use
> variables:
>
> myModule = __import__(moduleName)
> myMethod = operator.methodcaller(methodName)
> val = myMethod(myModule)
>
>
> This would be simpler, and probably faster too:
>
> myModule = __import__(moduleName)
> val = getattr(myModule, methodName)()
>
>
> It's certainly easier to read.
>
>
>> ---------------------------
>>
>> Apporach 2:
>> ---------------------------
>> moduleName = 'mymodule'    #These two variables are read from conf file.
>> methodName = 'mymethod'
>>
>> val = eval('myModule.' + methodName + '()')
>> print val
>
> This example also fails, since you don't have anything called "myModule".
>
> I suspect you left out a line, myModule = __import__(moduleName).
>
>
>> ---------------------------
>>
>> Question: Which approach is better and why. Is there any other better
>> way to do this?
>
>
> You should avoid eval, it is a massive security risk unless you are an
> expert, and even then it is still a big security risk. It's also slower
> than the alternatives.
>
>
> --
> Steven
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list