Want to check that our code follows style rules
And doesn’t do things that are likely to be bugs
Build a [%g linter “linters” %]
[%x check %] represented HTML as a [%g dom “DOM tree” %]
We can represent code as an [%g abstract_syntax_tree “abstract syntax tree” %] (AST)
Each node represents a syntactic element in the program
[%inc simple.py %]
[% figure slug=“lint-ast-simple” img=“ast_simple.svg” alt=“Simple AST” caption=“The abstract syntax tree for a simple Python program.” %]
[%inc dump_ast.py %] [%inc dump_ast_simple.out head=“10” %]
Could walk the tree to find FunctionDef nodes and
record their name properties
But each node has a different structure, so we would have to write a recursive function for each type of node
[ast][py_ast] module’s ast.NodeVisitor
implements the [%g visitor_pattern “Visitor” %] pattern
Each time it reaches a node of type Thing, it looks
for a method visit_Thing
[%inc walk_ast.py mark=class %]
CollectNames constructors invokes
NodeVisitor constructor before doing anything else
visit_Assign and visit_FunctionDef must
call self.generic_visit(node) explicitly to
recurse
position methods uses the fact that every AST node
remembers where it came from
[%inc walk_ast.py mark=main %] [%inc walk_ast.sh %] [%inc walk_ast.out %]
[%inc has_duplicate_keys.py %]
[%inc has_duplicate_keys.out %]
[%inc find_duplicate_keys.py mark=class %] [%inc find_duplicate_keys.out %]
[%inc function_keys.py %]
Not wrong, but clutter makes code harder to read
Have to take [%g scope “scope” %] into account
So keep a stack of scopes
[%inc find_unused_variables.py mark=class %]
namedtuple from Python’s standard library[%inc find_unused_variables.py mark=scope %]
If the variable’s value is being read, node.ctx
(short for “context”) is an instance of Load
If the variable is being written to, node.ctx is an
instance of Store
[%inc find_unused_variables.py mark=name %]
[%inc find_unused_variables.py mark=search %]
[% figure slug=“lint-concept-map” img=“concept_map.svg” alt=“Concept map for code manipulation” caption=“Concept map.” %]