Python 3 reference · Built-in Functions

Python compile() Function

Compile source code into a code object that exec() or eval() can run. Mostly used by tools, REPLs and teaching examples.

Python 3 Since 3.0

Syntax

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

Parameters

ParameterDescription
source A string, bytes or an AST object.
filename Shown in tracebacks; use "<string>" for code that didn't come from a file.
mode "exec" for statements, "eval" for a single expression, "single" for one interactive statement.
flags, dont_inherit, optimize optional Advanced options for future features and optimization.

Return value

A code object.

Examples

Compile an expression once, evaluate it laterTry it yourself
code = compile("x * 2 + 1", "<string>", "eval")
print(eval(code, {"x": 10}))

Output

21
Compile statementsTry it yourself
code = compile("for i in range(3):\n    print(i)", "<loop>", "exec")
exec(code)

Output

0
1
2
Check syntax without runningTry it yourself
try:
    compile("print('missing paren'", "<demo>", "exec")
except SyntaxError as e:
    print("SyntaxError at line", e.lineno)

Output

SyntaxError at line 1

Security

Never compile and run text from users or the network: it can do anything your program can. To parse simple literal data, use ast.literal_eval() or json.loads() instead.

Version history

VersionChange
Python 3.0Added