Python Reference Library →

Python compile() Function – Compile Source Code at Runtime

Let’s look at compile() function – compile source code at runtime

  1. Notice

    compile() turns source text into a code object. Execution is a separate step; the mode must match the kind of source.

  2. Try

    Follow the example, change its sample, and compare what happens.

  3. Check

    Explain the result and test your understanding.

Watch how it works

Focus on how the names, objects, and calculations change. We’ll inspect the printed output in the next section.

Explore the idea

Follow the code and watch its state change. Guided simulation.

Code
Python
source = "number = 3"
code = compile(source, "sample", "exec")
namespace = {}
exec(code, namespace)
print(namespace["number"])
Live state

Top-level scope

source→Object 1
code→Object 2
namespace→Object 3
Object 1 · str'number = 3'Object 2 · code<code object <module>, file "sample", line 1>Object 3 · dict{'number': 3}
This step

compile() turns source text into a code object. Execution is a separate step; the mode must match the kind of source.

Picture compile() function – compile source code at runtime

compile() turns source text into a code object. Execution is a separate step; the mode must match the kind of source.

Image brief

Alt text
A diagram for Python compile() Function – Compile Source Code at Runtime. Instructions: source = "number = 3" code = compile(source, "sample", "exec") namespace = {} exec(code, namespace) print(namespace["number"]). Displayed result: 3. The final example bindings are source --> object 1 (str); code --> object 2 (code); namespace --> object 3 (dict). object 1: 'number = 3'; object 2: <code object <module>, file "sample", line 1>; object 3: {'number': 3}
Image generation prompt
Create a clean educational illustration for a Python programming lesson titled "Python compile() Function – Compile Source Code at Runtime". Teaching focus: compile() turns source text into a code object. Execution is a separate step; the mode must match the kind of source. Depict exactly the relationships and labels in this reference diagram: EXAMPLE INSTRUCTIONS source = "number = 3" code = compile(source, "sample", "exec") namespace = {} exec(code, namespace) print(namespace["number"]) | v DISPLAYED RESULT 3 FINAL BINDINGS source --> object 1 (str) code --> object 2 (code) namespace --> object 3 (dict) object 1: 'number = 3' object 2: <code object <module>, file "sample", line 1> object 3: {'number': 3} Use a flat vector style, generous spacing, clear arrows and legible labels, with a restrained blue/teal palette on a plain background. The diagram must explain the programming idea accurately. Do not depict variables as boxes containing copied objects when they share a reference. Avoid mascots, decorative screenshots, logos, gradients and extra text. Landscape composition, approximately 3:2, suitable for a course card. Accessible description: A diagram for Python compile() Function – Compile Source Code at Runtime. Instructions: source = "number = 3" code = compile(source, "sample", "exec") namespace = {} exec(code, namespace) print(namespace["number"]). Displayed result: 3. The final example bindings are source --> object 1 (str); code --> object 2 (code); namespace --> object 3 (dict). object 1: 'number = 3'; object 2: <code object <module>, file "sample", line 1>; object 3: {'number': 3}

Follow the execution

Choose a different sample input, then follow every step through to the output. Before revealing it, predict what the program will display.

Execution workspace

Choose a sample and follow its execution. Guided simulation.

Code
Python
source = "number = 3"
code = compile(source, "sample", "exec")
namespace = {}
exec(code, namespace)
print(namespace["number"])
Live state

Top-level scope

source→Object 1
code→Object 2
namespace→Object 3
Object 1 · str'number = 3'Object 2 · code<code object <module>, file "sample", line 1>Object 3 · dict{'number': 3}
This step

The example has finished. Compare the final output with the values and references above.

Terminal
Output
3

What do you expect this program to print?

What does this example display?

source = "number = 3"
code = compile(source, "sample", "exec")
namespace = {}
exec(code, namespace)
print(namespace["number"])
What does this example display?
Choose one answer. You can try again.

Answer and explanation

3

Follow the printed values in order. The output is: 3

Which explanation matches what you learned?

Which explanation matches what you learned?
Choose one answer. You can try again.

Answer and explanation

compile() turns source text into a code object. Execution is a separate step; the mode must match the kind of source.

compile() turns source text into a code object. Execution is a separate step; the mode must match the kind of source.

More examples and reference

Python compile() Function

The compile() function in Python is used to compile source code into a code object that can be executed using the exec() or eval() functions.

This is especially useful when you want to execute Python code that is available as a string.

Syntax

compile(source, filename, mode)

Parameters:

  • source: A string or AST object containing valid Python code.
  • filename: A name string (usually '<string>' if reading from a string).
  • mode: One of 'exec', 'eval', or 'single'.

Returns:

  • A code object which can be passed to exec() or eval().

Modes Explained

  • 'exec': For statements (like loops, function definitions).
  • 'eval': For expressions (like 2 + 2).
  • 'single': For a single interactive statement (like in the REPL).

Example 1: Using compile() with 'eval'

code = "3 + 5"
compiled_code = compile(code, "", "eval")
result = eval(compiled_code)
print(result)
8

Example 2: Using compile() with 'exec'

code = """
for i in range(3):
    print("Line", i)
"""
compiled = compile(code, "", "exec")
exec(compiled)
Line 0
Line 1
Line 2

Example 3: Using compile() with 'single'

code = "print('Hello')"
compiled = compile(code, "", "single")
exec(compiled)
Hello

Use Cases

  • Dynamically executing user-generated Python code.
  • Building a code editor, REPL, or interactive shell.
  • Converting strings into executable logic.

Common Mistakes

  • Using 'eval' for code that includes statements like if or for will raise a SyntaxError.
  • Always validate untrusted code before executing.

Interview Tip

In advanced interviews or coding tools, compile() is used to simulate a mini Python interpreter. It shows your understanding of dynamic code execution.

Summary

  • compile() turns code strings into code objects.
  • Use eval() or exec() to run the compiled code.
  • Modes: 'exec' (statements), 'eval' (expressions), 'single' (REPL).

Practice Problem

Write a program that reads an arithmetic expression from the user, compiles it, and evaluates the result.

user_input = input("Enter an arithmetic expression: ")
code_obj = compile(user_input, "", "eval")
result = eval(code_obj)
print("Result:", result)

What to remember

Connect what you noticed in the example with the idea below.

Remember

compile() turns source text into a code object. Execution is a separate step; the mode must match the kind of source.

Watch out for this idea

compile() always immediately executes the source code.

This is the misconception to avoid.

Reference checks are optional and do not count toward course progress.

    Reference library →