CodeBlanks Logo Icon CodeBlanks

compile

Learn to turn AST into executable code with compile().

What is compile?

compile turns an AST or a code string into an executable code object. It takes three arguments: source, filename and mode ("exec", "eval" or "single").

Mode "exec" runs multiple statements; "eval" evaluates a single expression. You run the resulting code object with exec or eval. Transforming an AST and recompiling it is a powerful technique for code generation and macro-like tools.

From AST to code object

You compile an AST with compile(tree, "<test>", "exec"). The second argument is the filename; it shows up in error messages, usually a name like "<test>". The third is the mode.

You run the resulting code object with exec(code, ns) in a namespace. The ns dict holds variables; you access them with ns["result"]. This flow — parse, transform, compile, run — is the classic chain of code-processing tools. It is flexible because each step is separately controllable.

Practice Run an AST with compile

Import the module with import ast. Build the tree with ast.parse("sonuc = 6 * 7"). Produce a code object with compile(tree, "<test>", "exec"). Run exec(code, ns) in an ns = {} dict and print ns["sonuc"].

Starter code

main.py
# compile the tree and run it
# print the result

Sample solution

main.py
import ast

tree = ast.parse("sonuc = 6 * 7")
code = compile(tree, "<test>", "exec")
ns = {}
exec(code, ns)
print(ns["sonuc"])

Expected output

42

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match compile concepts

Term Meaning
compile Turns into code
exec Multiple statements
eval Single expression
code object Executable

2 Complete the compile call

Question
code = ____(tree, "<test>", "exec")
Answer
code = compile(tree, "<test>", "exec")

Explanation: compile(tree, file, mode) produces a code object.

3 What does compile mode 'exec' do?

main.py
code = compile("x = 1
y = 2", "<t>", "exec")
ns = {}
exec(code, ns)
print(ns)
  • Raises an error
  • Runs multiple statements Correct answer
  • Evaluates one expression
  • Returns only a constant

Explanation: 'exec' mode runs multiple statements; 'eval' is for a single expression.

All lessons in Expert