2

Possible Duplicate:
What’s the difference between eval, exec, and compile in Python?

I known that

  1. eval is a function
  2. 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.

  1. 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 of eval, but I don't known why the eval can do this.

  2. 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?

Community
  • 1
  • 1
Tanky Woo
  • 4,906
  • 9
  • 44
  • 75

1 Answers1

3

The part of your question about storing the function name can be explained by the fact that this would be equivalent:

def test():
    print 'hello world'
func = test
func() # this will call test()

The call to eval() in your example is no different than a call like:

y = eval('x + 1')

I believe your second question is the same as this one, and the answers might be helpful.

Community
  • 1
  • 1
ford
  • 10,687
  • 3
  • 47
  • 54