Back to blog

Blog

UML Class Diagram From Code: Generate It, Then Fix It

Generate a UML class diagram from code with pyreverse, PlantUML or AI, then fix what static analysis gets wrong. Real commands, real output, one checklist.

UML class diagram from codeUpdated 11/20/2026Shafi Khan

UML Class Diagram From Code: Generate It, Then Fix It

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:

ApproachSource of truthStrengthWeak spot
Draw by handSomeone's memoryShows intent and hides noiseStale the moment code changes
Static extraction (pyreverse and friends)The parsed sourceDeterministic and repeatableLiteral, noisy, misses dynamic behaviour
AI from pasted codeThe model's reading of whatever you pastedFast, good at grouping and namingCan invent or drop relationships
Extract, then curateSource plus a human reviewerAccurate and readableNeeds 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 mmd picks the output format. Built-in formats are dot, puml, plantuml, mmd and html. Anything else (like png or svg) is handed to Graphviz, so you need Graphviz installed for image output.
  • -p shop sets the project name, which becomes part of the file names: classes_shop.mmd and packages_shop.mmd.
  • -d docs/diagrams sets the output directory. Create it first. In our run, pointing -d at 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 ALL shows private and protected members too. The default PUB_ONLY hides them, which is usually what you want for an architecture view.
  • -c PackageName.ClassName builds a diagram around one class and its related classes, instead of the whole package.
  • --max-depth N caps how deep into nested packages and modules the diagram goes, and --no-standalone drops classes with no connections. Together they're your anti-hairball lever.
  • -k shows 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:

RelationshipPlantUMLMeansCan a tool infer it?
Generalisation (inheritance)Parent <|-- ChildChild is-a ParentYes, reliably
RealisationInterface <|.. ImplImpl fulfils a contractOften, if the language has explicit interfaces
AssociationA --> BA holds a reference to BUsually, when types resolve
AggregationWhole o-- PartPart can outlive the wholeGuess at best
CompositionWhole *-- PartPart's lifecycle is owned by the wholeGuess at best
DependencyA ..> BA uses B briefly, e.g. a parameterPartially

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 OrderRepository interface 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:

  1. Run a deterministic extractor to get the factual skeleton.
  2. Ask AI to filter, group and label that skeleton, not to invent it from raw code.
  3. Diff the result against the extractor output. Any edge the AI added needs a line of code to justify it.
  4. 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 ALL for refactoring sessions.
  • It's text in Git. The .mmd or .puml file sits next to the code, so changes show up in pull requests.
  • Regeneration is scripted. One command, documented in the README or a make diagrams target.
  • 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-depth and --no-standalone to 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

FAQ

Questions readers ask before they act on this page.

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.

Related reading

Keep moving through the architecture workflow.

UML Class Diagram From Code: Generate It, Then Fix It | Architecto