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

L

Laxmikant Chitare

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
 
S

Steven D'Aprano

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



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

Laxmikant Chitare

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,955
Messages
2,570,117
Members
46,705
Latest member
v_darius

Latest Threads

Top