Precompile expressions
A service receives trusted expression text and needs to evaluate it repeatedly.
Python · Function
compile() turns source text, bytes, or an AST into a code object or AST object. The mode selects statement-sequence, expression, or interactive-statement compilation.
compile() transforms source text, bytes, or an AST into a code object or AST object. Choose the mode according to whether the input is a statement sequence, expression, or interactive statement; the returned code object can then be passed to exec() or eval().
compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1, *, module=None)| Name | Type | Description |
|---|---|---|
source | str | bytes | AST | Source text, bytes, or an AST object to compile. |
filename | str | Source filename label used for diagnostics. |
mode | str | Compilation mode: "exec", "eval", or "single". |
flags | int | Compiler flags to activate. |
dont_inherit | bool | Whether compiler options are inherited from the caller. |
optimize | int | Compiler optimization level. |
module | str | None | Optional module name. |
A code object or AST object.
source = "x + 2"
code = compile(source, "<string>", "eval")
result = eval(code)
print(result)Compiles an expression and evaluates the resulting code object.
A service receives trusted expression text and needs to evaluate it repeatedly.
A scripting tool builds a block of Python statements dynamically.
An interactive console processes one entered statement at a time.
compile() accepts a string, bytes object, or AST and returns a code object or AST object. The mode determines the accepted source shape: "exec" for statements, "eval" for one expression, and "single" for one interactive statement.
Follow-up: When would you use "eval" rather than "exec"? Use "eval" when the input is one expression whose resulting value is needed; use "exec" for a sequence of statements.
The filename argument labels the source for diagnostics and should identify the original file when applicable. For generated source, a recognizable value such as "<string>" is suitable.
Follow-up: Why should generated code still receive a filename? Tracebacks and syntax errors can expose that label, making the origin easier to diagnose.
flags and dont_inherit control compiler options and future-feature handling, while optimize selects the compiler optimization level. The module argument optionally supplies the module name.
Follow-up: What should callers do when compiling an AST? Follow the ast module documentation for constructing and working with AST objects.
execevalastast.AST