compile()
compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1) Returns:
code object · Added in v3.0 · Updated March 13, 2026 · Built-in Functions built-in code execution dynamic
The compile() function takes source code as a string or AST object and returns a code object. This code object can then be passed to exec() or eval() for execution. It’s useful for dynamically generating and executing Python code at runtime.
Syntax
compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
source | str or AST | — | A string containing Python source code, or an AST object |
filename | str | — | The filename used in error messages; typically <string> for inline code |
mode | str | — | One of 'exec', 'eval', or 'single' |
flags | int | 0 | Controls which future statements affect the compilation; use __future__ module constants |
dont_inherit | bool | False | If True, ignores inherited future statements |
optimize | int | -1 | Optimization level: -1 (default), 0 (no opt), 1 (-O), 2 (-OO) |
Mode Values
| Mode | Use For |
|---|---|
'exec' | Executing a statement or a sequence of statements |
'eval' | Evaluating a single expression |
'single' | Executing a single statement (like a REPL) |
Examples
Basic usage with exec
source_code = """
def greet(name):
return f"Hello, {name}!"
message = greet("World")
print(message)
"""
compiled = compile(source_code, "<string>", "exec")
exec(compiled)
# Hello, World!
Using eval with an expression
expression = "2 + 3 * 4"
compiled_expr = compile(expression, "<string>", "eval")
result = eval(compiled_expr)
print(result)
# 14
Dynamic function creation
source = """
def add(a, b):
return a + b
"""
code = compile(source, "<string>", "exec")
namespace = {}
exec(code, namespace)
add_function = namespace["add"]
print(add_function(5, 3))
# 8
Using flags for future statements
from __future__ import annotations
source = """
def foo(x: int) -> int:
return x * 2
"""
code = compile(source, "<string>", "exec", flags=0, dont_inherit=False)
Error handling with compile
bad_source = """
def broken(
return 42
"""
try:
compile(bad_source, "<string>", "exec")
except SyntaxError as e:
print(f"Syntax error at line {e.lineno}: {e.msg}")
# Syntax error at line 3: invalid syntax
Single mode for REPL-like behavior
source = "x = 5"
code = compile(source, "<string>", "single")
namespace = {}
exec(code, namespace)
print(namespace["x"])
# 5
Common Patterns
Template-based code generation
template = """
def {func_name}({params}):
\"\"\"Auto-generated function\"\"\"
return {result}
"""
source = template.format(
func_name="multiply",
params="a, b",
result="a * b"
)
code = compile(source, "<string>", "exec")
namespace = {}
exec(code, namespace)
print(namespace["multiply"](3, 7))
# 21
Conditional code execution
debug_mode = True
code = compile("print('Debug info')" if debug_mode else "pass", "<string>", "exec")
exec(code)
# Debug info
Compiling AST objects
import ast
source = "print('Hello from AST')"
tree = ast.parse(source)
compiled = compile(tree, "<string>", "exec")
exec(compiled)
# Hello from AST
Errors
| Error | When |
|---|---|
SyntaxError | Source code has invalid Python syntax |
TypeError | source is not a string or AST object, or mode is invalid |
ValueError | flags contains invalid bit values |
See Also
- built-in::exec — execute dynamically compiled code
- built-in::eval — evaluate a dynamically compiled expression