SyntaxStudy
Sign Up
Python AST and Code Introspection
Python Advanced 5 min read

AST and Code Introspection

Python AST

The ast module parses Python source into an Abstract Syntax Tree for analysis, transformation, and code generation.

Example
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()))
Pro Tip

Tools like Black, flake8, and mypy all use ast — understanding it unlocks custom linting rules.