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?

3
  • @avasal hello, I have seen this article, but I don't know the two examples im my question, you can see it. Commented Jan 22, 2013 at 10:18
  • @TankyWoo To add a new line add two spaces and start writing from the next line. :) Commented Jan 22, 2013 at 11:26
  • This questions asks about advanced usage of eval/exec which is not even mentioned in the proposed duplicate and it's examples, so it is NOT a duplicate, just way more specific. Commented Jun 10, 2014 at 15:15

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

But I don't know how func = eval(func) can make a str to function type?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.