Back
+20 XP
Concept

Inspecting Syntax Trees with `ast.dump`

Nested AST objects are difficult to read directly. `ast.dump(tree, indent=2)` prints formatted, human-readable syntax representations, exposing node types, targets, constants, and semantic contexts 🔍.

python
import ast

tree = ast.parse("x = 42")
print(ast.dump(tree, indent=2))

# 63. Inspecting Syntax Trees with `ast.dump` Nested AST objects are difficult to read directly. `ast.dump(tree, indent=2)` prints formatted, human-readable syntax representations, exposing node types, targets, constants, and semantic contexts 🔍. ```python import ast tree = ast.parse("x = 42") print(ast.dump(tree, indent=2)) ``` Notice `targets=[Name(id='x', ctx=Store())]`. If you reference `x` in an expression like `y = x`, its context flips to `Load()`. If you write `del x`, its context becomes `Del()` 🧠! --- ### Question What context (`ctx`) does a variable identifier receive in an AST when placed on the left side of an assignment? 🧠 - [ ] a. `ast.Store()`, signaling that the identifier is being assigned/written to 🔍 - [ ] b. `ast.Load()`, signaling that the value is being read from stack frames - [ ] c. `ast.Del()`, signaling immediate object deletion and ref-count decrements - [ ] d. `ast.Immutable()`, preventing re-assignment of the variable --- ### Challenge Parse `'x = 5'`. Inspect `tree.body[0].targets[0].ctx` and print its class name (`type(ctx).__name__`). 🎯 <details> <summary>Solution</summary> ```python import ast tree = ast.parse('x = 5') ctx = tree.body[0].targets[0].ctx print(type(ctx).__name__) ``` </details>

Checkpoint

What context (`ctx`) does a variable identifier receive in an AST when placed on the left side of an assignment? 🧠

Practice

Parse `'x = 5'`. Inspect `tree.body[0].targets[0].ctx` and print its class name (`type(ctx).__name__`). 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks