Parsing Python Code with `ast.parse`
An Abstract Syntax Tree (AST) represents source code structure as a hierarchical tree. `ast.parse(source)` converts raw code into an `ast.Module` tree containing expressions, assignments, and control flow nodes 🌳.
import ast
code = "result = a + 5"
tree = ast.parse(code)
assign = tree.body[0] # ast.Assign
print(f"Node: {type(assign).__name__} 🌳")
print(f"Target: {assign.targets[0].id}")
print(f"Operator: {type(assign.value.op).__name__}")
# 62. Parsing Python Code with `ast.parse` An Abstract Syntax Tree (AST) represents source code structure as a hierarchical tree. `ast.parse(source)` converts raw code into an `ast.Module` tree containing expressions, assignments, and control flow nodes 🌳. ```python import ast code = "result = a + 5" tree = ast.parse(code) assign = tree.body[0] # ast.Assign print(f"Node: {type(assign).__name__} 🌳") print(f"Target: {assign.targets[0].id}") print(f"Operator: {type(assign.value.op).__name__}") ``` Linters like Ruff and Flake8, type checkers like Mypy, and code formatters like Black all start by parsing your Python code into an AST with `ast.parse` ⚡! --- ### Question What is the top-level root node returned by `ast.parse()` when parsing Python code? 🧠- [ ] a. An `ast.Module` instance whose `.body` attribute contains top-level statement nodes 🌳 - [ ] b. An `ast.FunctionDef` wrapping an invisible entrypoint function - [ ] c. A dictionary storing variable identifiers mapped to heap pointers - [ ] d. A raw bytearray containing unlinked bytecode opcodes --- ### Challenge Parse the string `'y = 100'` using `ast.parse`. Access the integer constant via `tree.body[0].value.value` and print it. 🎯 <details> <summary>Solution</summary> ```python import ast tree = ast.parse('y = 100') print(tree.body[0].value.value) ``` </details>