Built-in Functions and Types

compile()

Translate source text, bytes or an AST into a code object, or request an AST using compiler flags. Compilation checks syntax and creates an executable representation without running its statements. Select eval for a single expression, exec for statements, or single for interactive input. SyntaxError indicates invalid syntax; invalid option values may raise ValueError. Use a descriptive filename for diagnostics.

Formal Syntax & Structure

python syntaxpython
compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)

Parameters & Attributes

NameTypeDescription
sourcestr | bytes | ASTSource or syntax tree to compile.
filenamestrDiagnostic label; need not name an existing file.
modestreval, exec or single.
flagsintCompiler flag bitmask; default 0.
dont_inheritboolIf true, do not inherit compiler flags from the caller.
optimizeint-1 uses interpreter settings; 0 normal, 1 removes asserts, 2 also removes docstrings.

Return Value

code object | AST

Compiled representation; AST-only flags can request a syntax tree.

Working Example

Example Snippetpython
# Local trusted-source demonstration; no dynamic input.code = compile("price * 2", "<pricing-example>", "eval")print(code.co_filename)print(code.co_names)try:    compile("value =", "<invalid-example>", "exec")except SyntaxError:    print("invalid syntax")
Python Reference