0
# mkdocstrings
1
2
A language-agnostic documentation generation system for MkDocs that automatically extracts and renders documentation from source code. mkdocstrings enables developers to embed API documentation directly into their Markdown files using a simple `::: identifier` syntax, supports multiple programming languages through extensible handlers, and offers cross-referencing capabilities both within projects and across external libraries.
3
4
## Package Information
5
6
- **Package Name**: mkdocstrings
7
- **Package Type**: pypi
8
- **Language**: Python
9
- **Installation**: `pip install mkdocstrings`
10
11
## Core Imports
12
13
```python
14
import mkdocstrings
15
```
16
17
For MkDocs plugin configuration:
18
19
```yaml
20
# mkdocs.yml
21
plugins:
22
- mkdocstrings
23
```
24
25
For direct extension usage:
26
27
```python
28
from mkdocstrings import MkdocstringsExtension, BaseHandler, Handlers
29
```
30
31
## Basic Usage
32
33
### As MkDocs Plugin
34
35
1. Install mkdocstrings:
36
```bash
37
pip install mkdocstrings
38
```
39
40
2. Configure in `mkdocs.yml`:
41
```yaml
42
plugins:
43
- mkdocstrings:
44
handlers:
45
python:
46
options:
47
docstring_style: google
48
```
49
50
3. Use in Markdown files:
51
```markdown
52
# My API Documentation
53
54
::: my_module.MyClass
55
options:
56
show_source: false
57
58
::: my_module.my_function
59
```
60
61
### Direct Extension Usage
62
63
```python
64
from markdown import Markdown
65
from mkdocstrings import MkdocstringsExtension, Handlers
66
67
# Create handlers instance
68
handlers = Handlers(
69
theme="material",
70
default="python",
71
inventory_project="my-project"
72
)
73
74
# Create and configure Markdown instance
75
md = Markdown(extensions=[
76
MkdocstringsExtension(handlers=handlers, autorefs=None)
77
])
78
79
# Process markdown with autodoc blocks
80
result = md.convert("""
81
::: my_module.MyClass
82
options:
83
show_source: false
84
""")
85
```
86
87
## Architecture
88
89
mkdocstrings follows a modular architecture centered around handlers and processors:
90
91
- **Plugin System**: `MkdocstringsPlugin` integrates with MkDocs build process
92
- **Extension System**: `MkdocstringsExtension` and `AutoDocProcessor` process `::: identifier` blocks in Markdown
93
- **Handler System**: `BaseHandler` and `Handlers` provide language-specific documentation extraction
94
- **Inventory System**: `Inventory` and `InventoryItem` enable cross-project documentation linking
95
- **Rendering System**: Tree processors and highlighters format the final output
96
- **Logging System**: Specialized loggers for templates and debugging
97
98
This modular design enables extensibility through custom handlers while maintaining consistent processing and rendering across different programming languages.
99
100
## Capabilities
101
102
### Plugin Integration
103
104
Core MkDocs plugin functionality for seamless integration with MkDocs sites, including configuration management, build process integration, and theme support.
105
106
```python { .api }
107
class MkdocstringsPlugin(BasePlugin[PluginConfig]):
108
def on_config(self, config: MkDocsConfig) -> MkDocsConfig | None: ...
109
def on_post_build(self, config: MkDocsConfig, **kwargs: Any) -> None: ...
110
def get_handler(self, handler_name: str) -> BaseHandler: ...
111
112
class PluginConfig(Config):
113
handlers = opt.Type(dict, default={})
114
default_handler = opt.Type(str, default="python")
115
custom_templates = opt.Optional(opt.Dir(exists=True))
116
enable_inventory = opt.Optional(opt.Type(bool))
117
enabled = opt.Type(bool, default=True)
118
locale = opt.Optional(opt.Type(str))
119
```
120
121
[Plugin Integration](./plugin-integration.md)
122
123
### Handler System
124
125
Extensible handler system for processing different programming languages, with base classes for creating custom handlers and a manager for handler lifecycle.
126
127
```python { .api }
128
class BaseHandler:
129
name: ClassVar[str] = ""
130
domain: ClassVar[str] = ""
131
enable_inventory: ClassVar[bool] = False
132
133
def collect(self, identifier: str, options: HandlerOptions) -> CollectorItem: ...
134
def render(self, data: CollectorItem, options: HandlerOptions, *, locale: str | None = None) -> str: ...
135
136
class Handlers:
137
def __init__(self, *, theme: str, default: str, inventory_project: str, ...): ...
138
def get_handler(self, name: str, handler_config: dict | None = None) -> BaseHandler: ...
139
```
140
141
[Handler System](./handler-system.md)
142
143
### Markdown Processing
144
145
Markdown extension and processors for parsing and rendering `::: identifier` autodoc blocks within Markdown documents.
146
147
```python { .api }
148
class MkdocstringsExtension(Extension):
149
def __init__(self, handlers: Handlers, autorefs: AutorefsPlugin, **kwargs: Any) -> None: ...
150
def extendMarkdown(self, md: Markdown) -> None: ...
151
152
class AutoDocProcessor(BlockProcessor):
153
def test(self, parent: Element, block: str) -> bool: ...
154
def run(self, parent: Element, blocks: MutableSequence[str]) -> None: ...
155
```
156
157
[Markdown Processing](./markdown-processing.md)
158
159
### Inventory and Cross-Referencing
160
161
Object inventory system for managing and cross-referencing documentation objects within and across projects.
162
163
```python { .api }
164
class Inventory(dict):
165
def __init__(self, items: list[InventoryItem] | None = None, project: str = "project", version: str = "0.0.0") -> None: ...
166
def register(self, name: str, domain: str, role: str, uri: str, priority: int = 1, dispname: str | None = None) -> None: ...
167
def format_sphinx(self) -> bytes: ...
168
169
class InventoryItem:
170
def __init__(self, name: str, domain: str, role: str, uri: str, priority: int = 1, dispname: str | None = None) -> None: ...
171
```
172
173
[Inventory System](./inventory-system.md)
174
175
### Rendering and Formatting
176
177
HTML rendering components including syntax highlighting, heading management, and output formatting processors.
178
179
```python { .api }
180
class Highlighter(Highlight):
181
def highlight(self, src: str, language: str | None = None, *, inline: bool = False, dedent: bool = True, linenums: bool | None = None, **kwargs: Any) -> str: ...
182
183
class HeadingShiftingTreeprocessor(Treeprocessor):
184
def __init__(self, md: Markdown, shift_by: int) -> None: ...
185
def run(self, root: Element) -> None: ...
186
```
187
188
[Rendering System](./rendering-system.md)
189
190
### Logging and Debugging
191
192
Specialized logging system designed for template environments and debugging mkdocstrings processing.
193
194
```python { .api }
195
class LoggerAdapter(logging.LoggerAdapter):
196
def __init__(self, prefix: str, logger: logging.Logger) -> None: ...
197
198
class TemplateLogger:
199
def __init__(self, logger: LoggerAdapter) -> None: ...
200
201
def get_logger(name: str) -> LoggerAdapter: ...
202
def get_template_logger(handler_name: str | None = None) -> TemplateLogger: ...
203
```
204
205
[Logging System](./logging-system.md)
206
207
## Types
208
209
### Core Types
210
211
```python { .api }
212
CollectorItem = Any # Type of item returned by handler's collect method
213
HandlerConfig = Any # Type for handler configuration
214
HandlerOptions = Any # Type for options passed to handlers
215
```
216
217
### Exception Types
218
219
```python { .api }
220
class CollectionError(Exception):
221
"""Raised when data collection fails."""
222
223
class ThemeNotSupported(Exception):
224
"""Raised when a theme is not supported."""
225
```
226
227
## Constants
228
229
```python { .api }
230
TEMPLATES_DIRS: Sequence[Path] # Directories where handler templates are located
231
```
232
233
## Utility Functions
234
235
```python { .api }
236
def do_any(seq: Sequence, attribute: str | None = None) -> bool:
237
"""Check if any item in sequence evaluates to True (Jinja filter)."""
238
239
def get_template_path(context: Context) -> str:
240
"""Return path to template using given context."""
241
242
def get_template_logger_function(logger_func: Callable) -> Callable:
243
"""Create wrapper function for template logging."""
244
```