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 " + m
Is this the reason:
import module_name
is a statement, not expression?
and:
eval
does only to calculate a expression
exec
does to run the statement in the str?