Search code examples
pythonbuilt-in

When to use "eval" mode rather than "exec" with Python compile()


Python's built-in compile function has eval, exec and single modes. single mode seems a bit useless (ref). How about the eval and exec?

  • eval: works on an expression
  • exec: works on statements

But an expression is a statement. My question is: why not just use exec all the time?

PS: I've read some related questions like Python built-in function "compile". What is it used for?. They do a good job explaining the difference between the modes, but doesn't directly answer my question.


Solution

  • Just like the eval builtin, the compile eval mode creates a code object that evaluates an expression and returns its result. In contrast, exec mode does not return a result.

    >>> exec_code = compile("1 + 2", "<stack overflow>", "exec")
    >>> eval(exec_code)  # no result for "exec" mode code
    >>> eval_code = compile("1 + 2", "<stack overflow>", "eval")
    >>> eval(eval_code)  # some result for "eval" mode code
    3
    

    But an expression is a statement.

    This is not true. An expression evaluates to a value, a statement does not.

    While expression statements mean an expression can be used "as a" statement, that does not make the two equivalent. An expression statement contains an expression; when run, the statement evaluates the expression but discards the result.