Reading — step 1 of 5
Read
~1 min readAST & Visitors
AST: Tree of Code
Python's ast module gives a tree:
python
Each node has:
- A type (
Assign,BinOp,Name,FunctionDef, ...). - Children (lists of nodes).
- Location (
lineno,col_offset,end_lineno,end_col_offset).
Visitor pattern:
python
generic_visit recurses; without it, you stop descent at this node.
NodeVisitor vs NodeTransformer:
- Visitor: read-only.
- Transformer: returns new node to REPLACE the visited one (for autofixers).
For other languages: tree-sitter is a portable parser library — same visitor model works across 50+ languages.
Important: AST loses some info — comments, blank lines, exact whitespace. Style linters need a CST (concrete syntax tree) or token stream alongside.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…