Entity relationship diagrams for Python data model classes like Pydantic.
npx @tessl/cli install tessl/pypi-erdantic@1.1.00
# Erdantic
1
2
## Overview
3
4
Erdantic is a Python library for automatically generating entity relationship diagrams (ERDs) from Python data model classes. It supports multiple popular data modeling frameworks including Pydantic V2, Pydantic V1 legacy, attrs, msgspec, and Python standard library dataclasses. The library uses Graphviz for rendering high-quality diagrams and offers both a convenient CLI interface and a comprehensive Python API for programmatic use.
5
6
The tool is particularly valuable for documentation purposes, allowing developers to visualize relationships between data models in their applications with clean, professional diagrams. It features automatic discovery of model relationships, customizable diagram styling, and support for complex nested data structures.
7
8
## Package Information
9
10
- **Name**: erdantic
11
- **Type**: Python library
12
- **Language**: Python
13
- **Installation**: `pip install erdantic`
14
- **Version**: 1.1.1
15
- **Dependencies**: Requires Graphviz system package and Python packages: pydantic >= 2, pydantic-core, pygraphviz, typer, typenames >= 1.3, sortedcontainers-pydantic, typing_extensions>4 (Python < 3.12)
16
17
## Core Imports
18
19
```python
20
import erdantic
21
```
22
23
## Common Imports
24
25
```python
26
from erdantic import EntityRelationshipDiagram, create, draw, to_dot
27
```
28
29
## Basic Usage
30
31
The most common use case is generating diagrams from data model classes using the convenience functions:
32
33
```python
34
from pydantic import BaseModel
35
from erdantic import draw
36
37
class User(BaseModel):
38
name: str
39
email: str
40
41
class Post(BaseModel):
42
title: str
43
author: User
44
tags: list[str]
45
46
# Generate and save diagram
47
draw(User, Post, out="my_models.png")
48
```
49
50
For programmatic control, use the main diagram class:
51
52
```python
53
from erdantic import EntityRelationshipDiagram
54
55
# Create diagram instance
56
diagram = EntityRelationshipDiagram()
57
diagram.add_model(User)
58
diagram.add_model(Post)
59
60
# Render to file
61
diagram.draw("output.svg")
62
63
# Get DOT language representation
64
dot_string = diagram.to_dot()
65
```
66
67
## Architecture
68
69
Erdantic's architecture consists of several key components:
70
71
- **Core Diagram System**: `EntityRelationshipDiagram` manages model information and relationships
72
- **Plugin System**: Extensible framework supporting different data modeling libraries through registered plugins
73
- **Convenience Layer**: High-level functions (`create`, `draw`, `to_dot`) for common operations
74
- **CLI Interface**: Command-line tool for generating diagrams from module/class paths
75
- **Type Analysis**: Utilities for analyzing type annotations and model relationships
76
77
## Capabilities
78
79
### [Diagram Creation](./diagram-creation.md)
80
Create and manage entity relationship diagrams programmatically. The core `EntityRelationshipDiagram` class provides methods to add models, analyze relationships, and maintain diagram state.
81
82
```python { .api }
83
class EntityRelationshipDiagram:
84
def add_model(self, model: type, recurse: bool = True) -> None:
85
"""Add a data model class to the diagram."""
86
87
def draw(self, out: Union[str, os.PathLike], graph_attr: Optional[Mapping[str, Any]] = None,
88
node_attr: Optional[Mapping[str, Any]] = None, edge_attr: Optional[Mapping[str, Any]] = None, **kwargs) -> None:
89
"""Render entity relationship diagram to file."""
90
91
def to_dot(self, graph_attr: Optional[Mapping[str, Any]] = None, node_attr: Optional[Mapping[str, Any]] = None,
92
edge_attr: Optional[Mapping[str, Any]] = None) -> str:
93
"""Generate DOT language representation of diagram."""
94
```
95
96
### [Convenience Functions](./convenience-functions.md)
97
High-level functions for quick diagram generation without managing diagram instances directly. These functions automatically create diagrams, analyze models, and produce output.
98
99
```python { .api }
100
def create(*models_or_modules: Union[type, ModuleType], terminal_models: Collection[type] = tuple(),
101
termini: Collection[type] = tuple(), limit_search_models_to: Optional[Collection[str]] = None) -> EntityRelationshipDiagram:
102
"""Construct EntityRelationshipDiagram from given data model classes or modules."""
103
104
def draw(*models_or_modules: Union[type, ModuleType], out: Union[str, os.PathLike],
105
terminal_models: Collection[type] = tuple(), termini: Collection[type] = tuple(),
106
limit_search_models_to: Optional[Collection[str]] = None,
107
graph_attr: Optional[Mapping[str, Any]] = None, node_attr: Optional[Mapping[str, Any]] = None,
108
edge_attr: Optional[Mapping[str, Any]] = None, **kwargs) -> None:
109
"""Render entity relationship diagram for given data model classes to file."""
110
111
def to_dot(*models_or_modules: Union[type, ModuleType], terminal_models: Collection[type] = [],
112
termini: Collection[type] = tuple(), limit_search_models_to: Optional[Collection[str]] = None,
113
graph_attr: Optional[Mapping[str, Any]] = None, node_attr: Optional[Mapping[str, Any]] = None,
114
edge_attr: Optional[Mapping[str, Any]] = None) -> str:
115
"""Generate DOT language representation of entity relationship diagram."""
116
```
117
118
### [Plugin System](./plugin-system.md)
119
Extensible framework for supporting different data modeling libraries. Plugins provide predicates to identify model types and extractors to analyze model fields.
120
121
```python { .api }
122
def list_plugins() -> list[str]:
123
"""List the keys of all registered plugins."""
124
```
125
126
### [Command Line Interface](./cli.md)
127
Command-line tool for generating diagrams from fully qualified model/module names. Supports various output formats and customization options.
128
129
```python { .api }
130
# CLI entry point: erdantic [models_or_modules...] --out OUTPUT_FILE [options]
131
```
132
133
### [Model Information Classes](./model-info.md)
134
Internal data structures representing analyzed models, fields, and relationships. These classes provide the foundation for diagram generation and can be used for advanced programmatic manipulation.
135
136
```python { .api }
137
class ModelInfo:
138
full_name: FullyQualifiedName
139
name: str
140
fields: dict[str, FieldInfo]
141
description: str
142
143
class FieldInfo:
144
model_full_name: FullyQualifiedName
145
name: str
146
type_name: str
147
148
class Edge:
149
source_model_full_name: FullyQualifiedName
150
source_field_name: str
151
target_model_full_name: FullyQualifiedName
152
target_cardinality: Cardinality
153
target_modality: Modality
154
```
155
156
### [Exception Classes](./exceptions.md)
157
Exception classes that provide specific error information when operations fail. Essential for error handling and troubleshooting issues with model analysis and diagram generation.
158
159
```python { .api }
160
class ErdanticException(Exception): ...
161
class UnknownModelTypeError(ValueError, ErdanticException): ...
162
class PluginNotFoundError(KeyError, ErdanticException): ...
163
class ModelOrModuleNotFoundError(ImportError, ErdanticException): ...
164
class UnresolvableForwardRefError(NameError, ErdanticException): ...
165
class UnevaluatedForwardRefError(ErdanticException): ...
166
class FieldNotFoundError(AttributeError, ErdanticException): ...
167
```