Possible Duplicate:
What’s the difference between eval, exec, and compile in Python?
I known that
- eval is a
function - exec is a
statement
And the simple usage of both is :
eval('1+2')
exec 'print 1+2'
But there are other usages that I can’t understand.
-
Using a variable to store a function name, and using this variable to
call the function
eg:def test(): print 'hello world' func = 'test' func = eval(func) func() # this will call test()I type(func) after
func = eval(func)
it returns
<type 'function'>
I read the document ofeval, but I don’t known why the eval can do
this. -
Using a variable to store a module name, and using this variable to import the module.
eg.m = 'sys' exec "import " + mIs this the reason:
import module_nameis a statement, not expression?
and:
evaldoes only to calculate a expression
execdoes to run the statement in the str?
The part of your question about storing the function name can be explained by the fact that this would be equivalent:
The call to
eval()in your example is no different than a call like:I believe your second question is the same as this one, and the answers might be helpful.