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

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

Asked on November 10, 2018 in Python.
Add Comment


  • 1 Answer(s)

    Here exec is not an expression: a statement in Python 2.x, and a function in Python 3.x.
    It compiles and then immediately evaluates a statement or set of statement contained in a string.
    For 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.
    

    eval is a built-in function (not a statement), which check out 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.
    

    Compile is a low level version of exec and eval and it will not execute or evaluate your statements or expressions, but returns a code object that can do it. The modes are as follows:

    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.

    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.

    compile(string, ”, ‘single’) is like the exec mode, but it will ignore everything except for the first statement. Note that an if/else statement with its results is considered a single statement.

     

    Answered on November 10, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.