A UML class diagram from code is a 30-second job: point an extractor like pyreverse at your package, get Mermaid or PlantUML text out, render it. The real work is the next ten minutes, where you fix what the tool got wrong and delete what nobody needs to see.
TL;DR: generate the skeleton automatically, curate it by hand, store it as text next to the code, and regenerate on every meaningful change. AI can speed up the curation step, but it should never be the only source of truth.
Why bother at all? Because the class diagram on your wiki is from the sprint where someone was "just tidying up the domain model". In 2023. Generated diagrams fix the staleness problem. Curated diagrams fix the "this is a hairball of 140 boxes" problem. You want both.
Why generate a UML class diagram from code instead of drawing it
Hand-drawn class diagrams have one fatal flaw: they describe the design someone meant to build. Generated ones describe what actually shipped. That gap is exactly where bugs, surprise coupling and onboarding pain live.
Here's how the main approaches stack up:
| Approach | Source of truth | Strength | Weak spot |
|---|---|---|---|
| Draw by hand | Someone's memory | Shows intent and hides noise | Stale the moment code changes |
| Static extraction (pyreverse and friends) | The parsed source | Deterministic and repeatable | Literal, noisy, misses dynamic behaviour |
| AI from pasted code | The model's reading of whatever you pasted | Fast, good at grouping and naming | Can invent or drop relationships |
| Extract, then curate | Source plus a human reviewer | Accurate and readable | Needs a review habit |
The last row is the move. Extraction gets you honesty, curation gets you signal.
UML itself is a stable target, by the way. The current formal version from the Object Management Group is UML 2.5.1, published December 2017. The notation is not going to shift under your feet.
→ Keep generated and hand-modelled diagrams side by side in Flow IQ's UML designer
Generate a UML class diagram with pyreverse (Python)
If you write Python, you already have a decent extractor installed: pyreverse ships with pylint. It parses your package and writes class and package diagrams.
Take this small domain module, shop/models.py:
from dataclasses import dataclass
@dataclass
class LineItem:
sku: str
qty: int
class Order:
def __init__(self, customer: "Customer"):
self.customer = customer
self.items: list[LineItem] = []
def add(self, item: LineItem) -> None:
self.items.append(item)
class Customer:
def __init__(self, email: str):
self.email = email
class PriorityOrder(Order):
pass
Generate a Mermaid class diagram:
pip install pylint
mkdir -p docs/diagrams
pyreverse -o mmd -p shop -d docs/diagrams shop
What the flags do:
-o mmdpicks the output format. Built-in formats aredot,puml,plantuml,mmdandhtml. Anything else (likepngorsvg) is handed to Graphviz, so you need Graphviz installed for image output.-p shopsets the project name, which becomes part of the file names:classes_shop.mmdandpackages_shop.mmd.-d docs/diagramssets the output directory. Create it first. In our run, pointing-dat a folder that didn't exist printed the analysis summary and quietly wrote nothing.
Here's the classes_shop.mmd it produced with pylint 4.1:
classDiagram
class Customer {
email : str
}
class LineItem {
qty : int
sku : str
}
class Order {
customer : str
items : list[LineItem]
add(item: LineItem) None
}
class PriorityOrder {
}
PriorityOrder --|> Order
Order --> LineItem : items
Spot the bug? customer : str. The quoted forward reference "Customer" got read as a string, and the Order to Customer relationship vanished. Switch to from __future__ import annotations with an unquoted customer: Customer, rerun, and the edge comes back as Customer --o Order : customer.
That's the whole lesson of this post in one diff. The tool is honest about what it can resolve, and nothing more.
Useful flags once the project grows:
-f ALLshows private and protected members too. The defaultPUB_ONLYhides them, which is usually what you want for an architecture view.-c PackageName.ClassNamebuilds a diagram around one class and its related classes, instead of the whole package.--max-depth Ncaps how deep into nested packages and modules the diagram goes, and--no-standalonedrops classes with no connections. Together they're your anti-hairball lever.-kshows class names only. Perfect for big-picture slides.
→ Map the wider repository structure and hotspots with Code Analysis
PlantUML class diagram from code: the same model, different renderer
Prefer PlantUML? Swap the format:
pyreverse -o puml -p shop -d docs/diagrams shop
You get a classes_shop.puml wrapped in @startuml / @enduml, with fully qualified aliases like shop.models.Order and the same relationships. PlantUML is handy when your docs toolchain already renders it, or when you want the richer arrow vocabulary for hand edits.
PlantUML's class diagram reference defines the visibility markers you'll see after -f ALL: + public, - private, # protected, ~ package private.
Mermaid or PlantUML is mostly a rendering decision, not a modelling one. Pick whatever your wiki, README or docs site renders natively, so the diagram lives where people actually read. If you're weighing the two camps more broadly, our breakdown of architecture diagram as code vs drag-and-drop tools covers the trade-offs.
→ Compare Architecto and Mermaid Chart for text-first diagramming
UML class diagram relationships explained (and what tools can't infer)
This is where generated diagrams most often lie by omission. Extractors see types and references. They don't see intent. Here's the PlantUML notation and what a human has to decide:
| Relationship | PlantUML | Means | Can a tool infer it? |
|---|---|---|---|
| Generalisation (inheritance) | Parent <|-- Child | Child is-a Parent | Yes, reliably |
| Realisation | Interface <|.. Impl | Impl fulfils a contract | Often, if the language has explicit interfaces |
| Association | A --> B | A holds a reference to B | Usually, when types resolve |
| Aggregation | Whole o-- Part | Part can outlive the whole | Guess at best |
| Composition | Whole *-- Part | Part's lifecycle is owned by the whole | Guess at best |
| Dependency | A ..> B | A uses B briefly, e.g. a parameter | Partially |
Look back at our output: Order --> LineItem is a plain association. But in the domain, line items die with their order. That's composition, and only you know it. Meanwhile pyreverse labelled Customer as aggregation, which happens to be right (customers outlive orders), but you should confirm it rather than trust it.
The curation pass is basically this table, applied edge by edge. Five minutes, huge clarity gain.
→ Re-model relationships with intent in Flow IQ instead of fighting raw output
Can AI generate UML diagrams from code?
Short answer: yes, and it's useful. Longer answer: it's useful as a drafting and curation tool, not as the source of truth.
Where large language models shine:
- Grouping and naming. "Show me the payment domain only" is something an extractor can't do, and a model can.
- Explaining. Turning a dense diagram into a paragraph a new hire can follow.
- Picking diagram types. Deciding that a flow is better told as a sequence diagram than a class diagram (our sequence diagram examples show why).
Where they bite:
- Context limits. The model only sees what you paste. A relationship defined in another module simply doesn't exist to it.
- Plausible fiction. A model can draw an
OrderRepositoryinterface because that's what order systems usually have. Your codebase may not. - No diff discipline. Regenerating from scratch each time produces churn that's painful to review.
A workflow that holds up in review:
- Run a deterministic extractor to get the factual skeleton.
- Ask AI to filter, group and label that skeleton, not to invent it from raw code.
- Diff the result against the extractor output. Any edge the AI added needs a line of code to justify it.
- Commit the curated text. Regenerate the skeleton on change and re-check the diff.
For architecture-level views (services and modules, not classes), the same principle applies. We walk through it in how to reverse engineer architecture from code.
→ Turn repository context into grounded technical docs with CoDocs
A review checklist for generated class diagrams
Run this before a generated diagram goes anywhere near a design review:
- Scope is one question. "How do orders relate to fulfilment?" beats "the whole backend".
- Noise is cut. Framework base classes, DTOs and test doubles removed unless they matter to the question.
- Missing edges are hunted. Check string annotations, dependency injection wiring and dynamically set attributes.
- Diamonds are deliberate. Every aggregation and composition reflects real lifecycle ownership.
- Visibility matches the audience. Public members only for architecture reviews,
-f ALLfor refactoring sessions. - It's text in Git. The
.mmdor.pumlfile sits next to the code, so changes show up in pull requests. - Regeneration is scripted. One command, documented in the README or a
make diagramstarget. - It's linked from the decision. If the diagram supports an ADR or design doc, link it both ways.
That last one matters more than it looks. Diagrams without a decision attached drift into wallpaper. Our decision log best practices cover how to keep the two connected.
→ Build a reusable review checklist with the free Architecture Review Checklist Builder
Key takeaways
- A UML class diagram from code is easy to generate. Making it trustworthy is the actual job.
- pyreverse (bundled with pylint) outputs Mermaid, PlantUML, DOT and HTML. Use
-c,-k,--max-depthand--no-standaloneto keep diagrams readable. - Extractors are literal. Quoted type hints, DI containers and dynamic attributes hide relationships.
- Composition vs aggregation is a human decision. Tools guess. You know the lifecycle.
- AI is a great curator and explainer, and a risky sole author. Anchor it to deterministic output and diff everything.
- Keep the diagram as text, in Git, next to the code. That's what stops it becoming the diagram nobody updated since 2023.
→ See how Flow IQ's eight designers cover UML, sequence, schema and state diagrams
Ship diagrams your team will actually trust
Generated class diagrams answer "what is the code shaped like?". Architecture reviews also need "how does it run, what does it cost, and what can go wrong?". Architecto keeps those views together: Flow IQ for UML, sequence and schema diagrams, Code Analysis for repository structure and hotspots, and CoDocs for documentation grounded in your actual repo.
Start with one package, one diagram and one honest review pass. Then make regeneration boring.
→ Start free and model your first UML diagram in Architecto
FAQ
How do I generate a UML class diagram from code?
Use a static extraction tool that reads your source and emits diagram text. For Python, pyreverse (shipped with pylint) writes Mermaid, PlantUML, DOT or HTML class diagrams with a command like pyreverse -o mmd -p myproject -d out mypackage. Commit the generated text, render it, then review the relationships by hand, because extraction tools report what the code literally says, not what the design intends.
Can AI generate UML diagrams from code?
Yes, large language models can draft class and sequence diagrams from pasted code, and they are good at naming and grouping. They can also invent relationships that do not exist or miss ones hidden in other files. Treat AI output as a draft, cross-check it against a deterministic extractor or the code itself, and keep the final diagram as reviewable text.
Why is my generated class diagram missing relationships?
Static extractors only see what they can resolve. String forward references, dynamic attributes, dependency injection containers and duck typing often hide edges. In our test, pyreverse rendered a quoted type hint as a plain str field and dropped the association until the annotation was a real type.
What is the difference between composition and aggregation in UML?
Both say one class holds another. Composition (a filled diamond, *-- in PlantUML) means the part's lifecycle is owned by the whole, like order line items that die with the order. Aggregation (a hollow diamond, o-- in PlantUML) means the part can exist independently, like a customer who outlives any single order. Code alone rarely tells a tool which one you meant.
→ Try Flow IQ free and turn your next class diagram into a reviewable artifact