Reading — step 1 of 5
Read
~1 min readAST & Visitors
Scope Analysis
A scope is a region where names are visible. Python scopes: module, function, class, comprehension.
Many lint rules need scope info:
- Unused variables:
x = 1andxnever read. - Undefined names:
print(typo_var). - Shadowing: inner
xshadows outerx(sometimes intentional, sometimes a bug).
Build a scope tree:
python
Walk AST, push scope on FunctionDef/ClassDef/Lambda, pop on exit. Track:
Assign,AugAssign, function args,for x in ...-> def in current scope.Name(ctx=Load)-> read in current scope (resolve via lookup).Global/Nonlocaldeclarations alter resolution.
Unused detection:
python
Real linters (like pyflakes) track this carefully. False positives include:
- Function args declared for interface compatibility.
- Pattern matching unused captures.
- Loop variables not used in body.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…