Backend & AI Engineer Guide: Parsing Python AST to Generate Mermaid UML & Code Graphs
Manually drawn architecture and database class diagrams go stale within weeks of a sprint, while feeding raw 200,000-line repositories into an LLM context window without structural indexing wastes tokens and misses cross-file inheritance chains. By parsing source code directly into an Abstract Syntax Tree (AST) using Python's built-in ast module (or Tree-sitter), we can deterministically extract class hierarchies, Django/SQLAlchemy ORM relationships, and typed method signatures—emitting live Mermaid.js UML class diagrams and structural graphs for AI coding agents. As a Senior Backend Engineer and AI Application Engineer, here is how I build automated AST documentation and code-intelligence pipelines.
1. Walking Python's ast.NodeVisitor Without Importing Untrusted Modules
Unlike runtime reflection (inspect.getmembers()), which requires importing modules and executing top-level side effects, ast.parse() analyzes source files purely statically in milliseconds:
import ast
from dataclasses import dataclass, field
@dataclass
class ParsedClassNode:
name: str
bases: list[str] = field(default_factory=list)
attributes: list[tuple[str, str]] = field(default_factory=list)
methods: list[str] = field(default_factory=list)
class MermaidClassExtractor(ast.NodeVisitor):
def __init__(self) -> None:
self.classes: list[ParsedClassNode] = []
def visit_ClassDef(self, node: ast.ClassDef) -> None:
bases = [ast.unparse(b) for b in node.bases]
cls_info = ParsedClassNode(name=node.name, bases=bases)
for item in node.body:
if isinstance(item, ast.AnnAssign) and isinstance(item.target, ast.Name):
ann_type = ast.unparse(item.annotation)
cls_info.attributes.append((item.target.id, ann_type))
elif isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef)):
cls_info.methods.append(item.name)
self.classes.append(cls_info)
self.generic_visit(node)
def generate_mermaid_class_diagram(source_code: str) -> str:
tree = ast.parse(source_code)
extractor = MermaidClassExtractor()
extractor.visit(tree)
lines = ["classDiagram"]
for cls in extractor.classes:
lines.append(f" class {cls.name} {{")
for attr_name, attr_type in cls.attributes:
lines.append(f" +{attr_type} {attr_name}")
for method_name in cls.methods:
lines.append(f" +{method_name}()")
lines.append(" }")
for base in cls.bases:
clean_base = base.split(".")[-1]
lines.append(f" {clean_base} <|-- {cls.name}")
return "
".join(lines)
2. Powering GraphRAG Codebase Indexing for AI Engineering Agents
When building AI developer tools or automated code-review agents, AST extraction serves as the structural backbone: every ClassDef and FunctionDef node is indexed by its fully qualified symbol path alongside its callers and callees, enabling pinpoint context retrieval when debugging or refactoring large monoliths.
3. Hire a Senior Backend & AI Engineer for Developer Tooling
Building static analysis pipelines, automated architecture documentation, or AI code assistants? Explore my Backend Engineer Pillar Guide, review my Mermaid Architecture Diagramming Guide, or book a 1-Day Engineering Tooling Sprint.