Python AST
The ast module parses Python source into an Abstract Syntax Tree for analysis, transformation, and code generation.
The ast module parses Python source into an Abstract Syntax Tree for analysis, transformation, and code generation.
import ast
source = "x = [i**2 for i in range(10) if i % 2 == 0]"
tree = ast.parse(source)
print(ast.dump(tree, indent=2))
# Find all function definitions
class FuncFinder(ast.NodeVisitor):
def visit_FunctionDef(self, node):
print(f"Function: {node.name} at line {node.lineno}")
self.generic_visit(node)
FuncFinder().visit(ast.parse(open("mymodule.py").read()))
Tools like Black, flake8, and mypy all use ast — understanding it unlocks custom linting rules.