Trace Source through Compilation
Core idea
In CPython 3.13, source is tokenized and parsed into an AST, scope is analyzed, and compiler passes produce code objects with instructions. Optimizations may fold constants or simplify control flow. Execution is a separate step; a code object is not native machine code. Public tools expose observations of stages rather than every internal intermediate representation.
import ast, typessource = 'result = 6 * 7'root = ast.parse(source)code = compile(root, '<lesson>', 'exec')namespace = {}print(isinstance(code, types.CodeType), 'result' in namespace)exec(code, namespace)print(namespace['result'])The namespace is unchanged until execution; the fixed local source is trusted.
Expected output:
True False42Observe constant folding
import ast, disroot = ast.parse('6 * 7', mode='eval')code = compile(root, '<lesson>', 'eval')print(type(root.body).__name__)print(any(i.opname in ('LOAD_CONST', 'RETURN_CONST') and i.argval == 42 for i in dis.get_instructions(code)))print(eval(code))The parsed tree contains multiplication; the pinned compiler emits the folded constant. The exact optimization is not a language guarantee.
Expected output:
BinOpTrue42Common mistake
Compilation and AST parsing can consume resources or fail. Do not execute arbitrary user input; the fixtures use fixed trusted source only.
Practice
Trace a fixed assignment containing two constants and one variable. Compare the AST and disassembly, then execute with an explicit namespace.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Compilation stages
Check your understanding of compilation stages.
What is printed?
import typesprint(isinstance(compile('x=1','<x>','exec'),types.CodeType))What is printed?
c=compile('x=1','<x>','exec')ns={}print('x' in ns)What does CPython normally execute from compiled Python source?
Is constant folding for every expression guaranteed?