What's the difference between eval, exec, and compile?

后端 未结 3 1844
梦谈多话
梦谈多话 2020-11-21 23:26

I\'ve been looking at dynamic evaluation of Python code, and come across the eval() and compile() functions, and the exec statement.

3条回答
  •  旧巷少年郎
    2020-11-22 00:16

    1. exec is not an expression: a statement in Python 2.x, and a function in Python 3.x. It compiles and immediately evaluates a statement or set of statement contained in a string. Example:

       exec('print(5)')           # prints 5.
       # exec 'print 5'     if you use Python 2.x, nor the exec neither the print is a function there
       exec('print(5)\nprint(6)')  # prints 5{newline}6.
       exec('if True: print(6)')  # prints 6.
       exec('5')                 # does nothing and returns nothing.
      
    2. eval is a built-in function (not a statement), which evaluates an expression and returns the value that expression produces. Example:

       x = eval('5')              # x <- 5
       x = eval('%d + 6' % x)     # x <- 11
       x = eval('abs(%d)' % -100) # x <- 100
       x = eval('x = 5')          # INVALID; assignment is not an expression.
       x = eval('if 1: x = 4')    # INVALID; if is a statement, not an expression.
      
    3. compile is a lower level version of exec and eval. It does not execute or evaluate your statements or expressions, but returns a code object that can do it. The modes are as follows:

    4. compile(string, '', 'eval') returns the code object that would have been executed had you done eval(string). Note that you cannot use statements in this mode; only a (single) expression is valid.

    5. compile(string, '', 'exec') returns the code object that would have been executed had you done exec(string). You can use any number of statements here.

    6. compile(string, '', 'single') is like the exec mode but expects exactly one expression/statement, eg compile('a=1 if 1 else 3', 'myf', mode='single')

提交回复
热议问题