Python compile Modes: exec vs eval vs single Explained

Python's built-in compile() function transforms source code strings into executable code objects that can later be passed to exec() or eval(). The behavior of this function is fundamentally governed by its mode parameter, which accepts one of three arguments: 'exec', 'eval', or 'single'. This parameter instructs the Python parser how to interpret the input syntax, what return behavior to expect, and how to handle expressions during execution.

The exec Mode

The 'exec' mode is designed for compiling arbitrary Python code, mimicking the execution of a standard Python module or script.

code_exec = compile("x = 5\ny = 10\nresult = x + y", "<string>", "exec")
namespace = {}
exec(code_exec, namespace)
print(namespace["result"])  # Outputs: 15

The eval Mode

The 'eval' mode strictly expects a single Python expression and evaluates it to produce a direct result.

code_eval = compile("5 * 10 + 2", "<string>", "eval")
output = eval(code_eval)
print(output)  # Outputs: 52

The single Mode

The 'single' mode emulates the behavior of the interactive Python interpreter (the REPL).

code_single = compile("40 + 2", "<string>", "single")
exec(code_single)  # Automatically prints: 42

Key Differences Summary

Feature exec eval single
Input Structure Multiple statements or script blocks Exactly one expression A single statement or semicolon-separated line
Allows Statements? Yes (loops, definitions, assignments) No (raises SyntaxError) Yes (typically single-line)
Execution Output Returns None Returns the expression result Displays the expression result if not None
Primary Consumer exec() eval() exec()