0
# Enhanced Autodoc
1
2
Modern Python feature documentation including Protocol, TypedDict, namedtuple, generics, and enhanced type hint processing. These extensions enable Sphinx to automatically document advanced Python typing features introduced in Python 3.5+ that aren't fully supported by standard autodoc.
3
4
## Capabilities
5
6
### Protocol Documentation
7
8
Automatic documentation for `typing.Protocol` classes with proper method signature extraction and inheritance handling.
9
10
```python { .api }
11
class ProtocolDocumenter(ClassDocumenter):
12
"""Autodocumenter for typing.Protocol classes."""
13
14
objtype = 'protocol'
15
directivetype = 'protocol'
16
priority = ClassDocumenter.priority + 1
17
18
@classmethod
19
def can_document_member(cls, member: Any, membername: str, isattr: bool, parent: Any) -> bool:
20
"""Check if member can be documented as Protocol."""
21
22
def add_content(self, more_content: Optional[StringList], no_docstring: bool = False) -> None:
23
"""Add Protocol-specific content including method signatures."""
24
25
def get_object_members(self, want_all: bool) -> Tuple[bool, List[Tuple[str, Any]]]:
26
"""Get Protocol members including abstract methods."""
27
```
28
29
Usage in code:
30
31
```python
32
from typing import Protocol
33
34
class Drawable(Protocol):
35
def draw(self) -> None:
36
"""Draw the object."""
37
...
38
```
39
40
In documentation:
41
42
```rst
43
.. autoprotocol:: mymodule.Drawable
44
:members:
45
```
46
47
### TypedDict Documentation
48
49
Specialized documenter for `typing.TypedDict` classes showing keys, types, and totality.
50
51
```python { .api }
52
class TypedDictDocumenter(ClassDocumenter):
53
"""Autodocumenter for TypedDict classes."""
54
55
objtype = 'typeddict'
56
directivetype = 'class'
57
priority = ClassDocumenter.priority + 1
58
59
@classmethod
60
def can_document_member(cls, member: Any, membername: str, isattr: bool, parent: Any) -> bool:
61
"""Check if member is a TypedDict."""
62
63
def add_content(self, more_content: Optional[StringList], no_docstring: bool = False) -> None:
64
"""Add TypedDict keys and type information."""
65
66
def get_type_comment(self, obj: Any) -> Optional[str]:
67
"""Get type comment for TypedDict keys."""
68
```
69
70
Usage in code:
71
72
```python
73
from typing import TypedDict
74
75
class PersonDict(TypedDict):
76
name: str
77
age: int
78
email: str
79
```
80
81
In documentation:
82
83
```rst
84
.. autotypeddict:: mymodule.PersonDict
85
```
86
87
### NamedTuple Documentation
88
89
Enhanced documentation for `collections.namedtuple` and `typing.NamedTuple` classes.
90
91
```python { .api }
92
class NamedTupleDocumenter(ClassDocumenter):
93
"""Autodocumenter for namedtuple classes."""
94
95
objtype = 'namedtuple'
96
directivetype = 'class'
97
priority = ClassDocumenter.priority + 1
98
99
@classmethod
100
def can_document_member(cls, member: Any, membername: str, isattr: bool, parent: Any) -> bool:
101
"""Check if member is a namedtuple."""
102
103
def add_content(self, more_content: Optional[StringList], no_docstring: bool = False) -> None:
104
"""Add namedtuple fields and type information."""
105
106
def document_members(self, all_members: bool = False) -> None:
107
"""Document namedtuple fields as attributes."""
108
```
109
110
Usage in code:
111
112
```python
113
from typing import NamedTuple
114
115
class Point(NamedTuple):
116
x: int
117
y: int
118
119
def distance_from_origin(self) -> float:
120
return (self.x ** 2 + self.y ** 2) ** 0.5
121
```
122
123
In documentation:
124
125
```rst
126
.. autonamedtuple:: mymodule.Point
127
:members:
128
```
129
130
### Generic Alias Documentation
131
132
Pretty printing and documentation for generic type aliases.
133
134
```python { .api }
135
class PrettyGenericAliasDocumenter(DataDocumenter):
136
"""Enhanced documentation for generic aliases like List[str], Dict[str, int]."""
137
138
objtype = 'genericalias'
139
directivetype = 'data'
140
priority = DataDocumenter.priority + 1
141
142
@classmethod
143
def can_document_member(cls, member: Any, membername: str, isattr: bool, parent: Any) -> bool:
144
"""Check if member is a generic alias."""
145
146
def add_content(self, more_content: Optional[StringList], no_docstring: bool = False) -> None:
147
"""Add pretty-printed generic alias information."""
148
149
def format_signature(self, **kwargs: Any) -> str:
150
"""Format generic alias signature."""
151
```
152
153
### Enhanced Type Hint Processing
154
155
Improved type hint formatting and cross-referencing in documentation.
156
157
```python { .api }
158
def format_annotation(annotation: Any, config: Config) -> str:
159
"""
160
Format type annotation for documentation.
161
162
Args:
163
annotation: Type annotation object
164
config: Sphinx configuration
165
166
Returns:
167
Formatted annotation string with proper cross-references
168
"""
169
170
def stringify_typehint(annotation: Any, mode: str = 'fully-qualified') -> str:
171
"""
172
Convert type hint to string representation.
173
174
Args:
175
annotation: Type annotation to stringify
176
mode: Formatting mode ('fully-qualified', 'smart', 'short')
177
178
Returns:
179
String representation of type hint
180
"""
181
182
def process_docstring(app: Sphinx, what: str, name: str, obj: Any, options: Any, lines: List[str]) -> None:
183
"""Process docstring to enhance type information."""
184
```
185
186
### Variable Documentation
187
188
Enhanced documentation for module-level variables and class attributes.
189
190
```python { .api }
191
class VariableDocumenter(DataDocumenter):
192
"""Enhanced documenter for variables with type annotation support."""
193
194
def add_content(self, more_content: Optional[StringList], no_docstring: bool = False) -> None:
195
"""Add variable type and value information."""
196
197
def get_type_annotation(self) -> Optional[str]:
198
"""Get type annotation for variable."""
199
200
def format_signature(self, **kwargs: Any) -> str:
201
"""Format variable signature with type information."""
202
```
203
204
### Source Link Integration
205
206
Automatic source code links for documented objects.
207
208
```python { .api }
209
def add_source_links(app: Sphinx, what: str, name: str, obj: Any, options: Any, lines: List[str]) -> None:
210
"""
211
Add source code links to documented objects.
212
213
Args:
214
app: Sphinx application
215
what: Type of object being documented
216
name: Object name
217
obj: Object being documented
218
options: Autodoc options
219
lines: Documentation lines
220
"""
221
222
class SourceLinkMixin:
223
"""Mixin class for adding source links to autodocumenters."""
224
225
def add_source_link(self) -> None:
226
"""Add source link to documentation."""
227
```
228
229
### TypeVar Documentation
230
231
Enhanced support for documenting TypeVar declarations.
232
233
```python { .api }
234
def process_typevars(app: Sphinx, what: str, name: str, obj: Any, options: Any, lines: List[str]) -> None:
235
"""
236
Process TypeVar declarations in documentation.
237
238
Args:
239
app: Sphinx application
240
what: Type of object
241
name: Object name
242
obj: Object being documented
243
options: Autodoc options
244
lines: Documentation lines
245
"""
246
247
class TypeVarDocumenter(DataDocumenter):
248
"""Specialized documenter for TypeVar objects."""
249
250
objtype = 'typevar'
251
directivetype = 'data'
252
```
253
254
### Function Overload Support
255
256
Documentation support for `@overload` decorated functions.
257
258
```python { .api }
259
def process_overloads(app: Sphinx, what: str, name: str, obj: Any, options: Any, lines: List[str]) -> None:
260
"""
261
Process function overloads for documentation.
262
263
Args:
264
app: Sphinx application
265
what: Type of object
266
name: Object name
267
obj: Function with overloads
268
options: Autodoc options
269
lines: Documentation lines
270
"""
271
272
class OverloadDocumenter(FunctionDocumenter):
273
"""Documenter that handles overloaded functions."""
274
275
def format_signature(self, **kwargs: Any) -> str:
276
"""Format all overload signatures."""
277
```
278
279
### Generic Base Class Support
280
281
Enhanced documentation for classes with generic base classes.
282
283
```python { .api }
284
class GenericBasesClassDocumenter(ClassDocumenter):
285
"""Documenter that properly handles generic base classes."""
286
287
def format_bases(self) -> Optional[str]:
288
"""Format generic base classes with proper type parameters."""
289
290
def get_type_params(self) -> List[str]:
291
"""Get type parameters from generic bases."""
292
```
293
294
### Configuration Options
295
296
Enhanced autodoc extensions add several configuration options:
297
298
```python
299
# Type hint processing
300
all_typevars = True
301
no_unbound_typevars = False
302
typehints_fully_qualified = False
303
typehints_use_signature = True
304
305
# Source links
306
source_link_target = "github" # "github" or "docs"
307
source_link_pattern = "https://github.com/{username}/{repository}/blob/{revision}/{path}#L{lineno}"
308
309
# Overload handling
310
overloads_location = "bottom" # "top", "bottom", or "signature"
311
312
# Generic alias formatting
313
generic_alias_formatting = "pretty"
314
```
315
316
### Error Handling
317
318
The enhanced autodoc extensions include proper error handling:
319
320
```python { .api }
321
class AutodocProcessingError(Exception):
322
"""Base exception for autodoc processing errors."""
323
324
class TypeHintError(AutodocProcessingError):
325
"""Raised when type hint processing fails."""
326
327
class GenericAliasError(AutodocProcessingError):
328
"""Raised when generic alias processing fails."""
329
```