Compiling ASTs into Bytecode with `compile()`
The built-in `compile(source, filename, mode)` compiles source strings or `ast.AST` trees directly into executable code objects. Code objects can then be evaluated instantly via `exec()` or `eval()` ⚡.
import ast
source = "total = sum([1, 2, 3, 4])"
tree = ast.parse(source)
# Compile AST into runnable bytecode
code_obj = compile(tree, filename="<ast>", mode="exec")
scope = {}
exec(code_obj, scope)
print(f"Total: {scope['total']} ⚡")
# 67. Compiling ASTs into Bytecode with `compile()` The built-in `compile(source, filename, mode)` compiles source strings or `ast.AST` trees directly into executable code objects. Code objects can then be evaluated instantly via `exec()` or `eval()` ⚡. ```python import ast source = "total = sum([1, 2, 3, 4])" tree = ast.parse(source) # Compile AST into runnable bytecode code_obj = compile(tree, filename="<ast>", mode="exec") scope = {} exec(code_obj, scope) print(f"Total: {scope['total']} ⚡") ``` Passing an existing `ast.AST` tree to `compile()` bypasses source-string re-tokenization entirely, enabling JIT-like macro rewriting and dynamic code generation pipelines 🏎️! --- ### Question What are the three canonical values for the `mode` parameter when calling `compile()`? 🧠 - [ ] a. `'exec'` for suites/modules, `'eval'` for expressions, and `'single'` for REPL interactive lines ⚡ - [ ] b. `'read'`, `'write'`, and `'append'` for stream redirection - [ ] c. `'strict'`, `'loose'`, and `'experimental'` for parser strictness - [ ] d. `'debug'`, `'release'`, and `'optimized'` for compiler flags --- ### Challenge Parse `'res = sum([1, 2, 3, 4])'`. Compile the AST to a code object with mode `'exec'`. Execute it in `scope = {}`. Print `scope['res']`. 🎯 <details> <summary>Solution</summary> ```python import ast tree = ast.parse('res = sum([1, 2, 3, 4])') co = compile(tree, '<test>', 'exec') scope = {} exec(co, scope) print(scope['res']) ``` </details>