Python compile() Function

Beginner
5 min read
Updated: Nov 2026
3 examples
Built-in

Definition

In Python, compile(source, filename, mode) parses source text and returns a code object: the bytecode form that eval() and exec() run. Compiling once and running many times saves re-parsing the same text.

The mode must be "eval" for one expression, "exec" for statements, or "single" for one interactive statement. filename is only a label used in tracebacks, such as "<formula>". Compiling does not run anything, so it is also a quick syntax check.

compile() is a built-in function: it lives in the builtins module, so it is always available without an import.

Syntax

Pass the source, a filename label, and a mode.

python
code_obj = compile(source, "<label>", "eval")
code_obj = compile(source, "<label>", "exec")
CallWhat it does
compile("1 + 2", "<x>", "eval")A code object for one expression.
eval(code_obj, ns)Runs an eval-mode code object.
compile(src, "<x>", "exec")A code object for statements.
compile(src, "<x>", "eval", ast.PyCF_ONLY_AST)Returns an AST instead.

Printing a code object shows a memory address; inspect attributes like co_filename or co_names instead.

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

Parameters

ParameterDescription
sourceRequired. A string, bytes, or AST object.
filenameRequired. Name shown in tracebacks; any string like "<string>".
modeRequired. "eval", "exec", or "single".
flagsOptional. Compiler flags, e.g. ast.PyCF_ONLY_AST.

Return Value

Return ValueDescription
code objectReady for eval() or exec() (or an AST when that flag is set).

Python Examples

Example 1 — Compile a Formula Once, Run It Many Times

Compile an expression in eval mode and evaluate it with different values.

python
expr = compile("x ** 2 + 1", "<formula>", "eval")
print(type(expr).__name__)

for x in [1, 2, 3]:
    print(x, eval(expr, {"x": x}))

How It Works

  1. Parsed once. The text is turned into a code object a single time.
  2. Type, not repr. Printing the type name avoids the address shown in a code object's repr.
  3. Reused. Each eval() runs the same compiled code with a new x.
  4. Fixed source. The formula is written by the programmer, never taken from users.

Example 2 — Compile Statements and Inspect the Code Object

Compile a small module, run it with exec(), and read two code-object attributes.

python
source = """
def double(n):
    return n * 2

result = double(21)
"""
code_obj = compile(source, "<generated>", "exec")
namespace = {}
exec(code_obj, namespace)

print(namespace["result"])
print(code_obj.co_filename)
print(sorted(code_obj.co_names))

How It Works

  1. Statements need exec mode. A def and an assignment are not expressions.
  2. Run separately. exec(code_obj, namespace) executes the compiled module.
  3. Label kept. co_filename is the label passed in; tracebacks show it.
  4. Names used. co_names lists the global names the code reads or writes.

Example 3 — Check Syntax Without Running Code

Compile snippets to detect syntax errors, then request an AST.

python
import ast

for snippet in ["total = 1 + 2", "total = (1 + ", "print('hi')"]:
    try:
        compile(snippet, "<check>", "exec")
        print(repr(snippet), "is valid")
    except SyntaxError:
        print(repr(snippet), "has a syntax error")

tree = compile("a + b", "<ast>", "eval", ast.PyCF_ONLY_AST)
print(type(tree).__name__, type(tree.body).__name__)

How It Works

  1. Nothing runs. Compiling only parses; the valid print snippet prints nothing.
  2. SyntaxError on bad text. The unclosed bracket is reported without executing anything.
  3. repr shows quotes. The third snippet contains single quotes, so its repr uses double quotes.
  4. AST mode. With PyCF_ONLY_AST, compile returns a syntax tree: an Expression whose body is a BinOp.

Frequently Asked Questions

A code object, which eval() or exec() can run. With the PyCF_ONLY_AST flag it returns an AST instead.
"eval" accepts a single expression; "exec" accepts any statements. "single" is for one interactive statement.
It is a label shown in tracebacks. Use something descriptive, such as "generated-config", for generated code.
Call compile(text, "check", "exec") inside try/except SyntaxError. Nothing is executed.
Compiling alone runs nothing, but executing the result is as dangerous as eval or exec. Do not run untrusted code.

Next: complex()

Create a complex number from parts or a string.

complex() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful