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

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

Asked on November 9, 2018 in Python.
Add Comment


  • 1 Answer(s)

    1. EXEC isn’t associate degree expression: an announcement in Python two.x, and a perform in Python three.x. It compiles and now evaluates an announcement or set of statement contained during 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 could be a lower level version of EXEC and eval. It doesn’t execute or valuate your statements or expressions, however returns a code object which will jazz. The modes square measure as follows:

        1. compile(string, ”, ‘eval’) returns the code object that will are dead had you done eval(string). Note that you      simply cannot use statements during this mode; solely a (single) expression is valid.

        2. compile(string, ”, ‘exec’) returns the code object that will are dead had you done exec(string). you’ll be able to use any variety of statements here.

        3. compile(string, ”, ‘single’) is just like the EXEC mode, however it’ll ignore everything aside from the primary statement. Note that associate degree if/else statement with its results is taken into account one statement.

    Answered on November 9, 2018.
    Add Comment


  • Your Answer

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