0
# Sphinx Extension
1
2
The numpydoc Sphinx extension provides comprehensive functionality for processing NumPy-style docstrings during documentation builds. It integrates seamlessly with Sphinx to transform NumPy docstrings into well-formatted reStructuredText.
3
4
## Core Setup
5
6
### Main Extension Setup
7
8
```python { .api }
9
def setup(app, *args, **kwargs):
10
"""
11
Main Sphinx extension setup function.
12
13
Registers numpydoc with Sphinx and configures all extension functionality
14
including docstring processing, signature handling, and custom domains.
15
16
Parameters
17
----------
18
app : sphinx.application.Sphinx
19
The Sphinx application instance
20
*args : tuple
21
Additional positional arguments (unused)
22
**kwargs : dict
23
Additional keyword arguments (unused)
24
25
Returns
26
-------
27
dict
28
Extension metadata with version and parallel read/write safety
29
"""
30
```
31
32
### Extension Entry Point
33
34
```python { .api }
35
# From numpydoc.__init__
36
from numpydoc import setup
37
38
def setup(app, *args, **kwargs):
39
"""
40
Package-level setup function that delegates to numpydoc.numpydoc.setup.
41
42
This is the main entry point when adding 'numpydoc' to extensions list.
43
"""
44
```
45
46
## Docstring Processing
47
48
### Core Processing Functions
49
50
```python { .api }
51
def mangle_docstrings(app, what, name, obj, options, lines):
52
"""
53
Process docstrings during Sphinx autodoc processing.
54
55
Transforms NumPy-style docstrings into reStructuredText format,
56
handling sections like Parameters, Returns, Examples, etc.
57
58
Parameters
59
----------
60
app : sphinx.application.Sphinx
61
Sphinx application instance
62
what : str
63
Type of object being documented ('module', 'class', 'function', etc.)
64
name : str
65
Fully qualified name of the object
66
obj : object
67
The actual Python object being documented
68
options : dict
69
Autodoc options for this object
70
lines : list of str
71
Docstring lines (modified in-place)
72
"""
73
74
def mangle_signature(app, what, name, obj, options, sig, retann):
75
"""
76
Process function signatures during Sphinx autodoc processing.
77
78
Handles signature mangling for better display, particularly for
79
functions with complex parameter lists or return annotations.
80
81
Parameters
82
----------
83
app : sphinx.application.Sphinx
84
Sphinx application instance
85
what : str
86
Type of object ('function', 'method', etc.)
87
name : str
88
Fully qualified name of the object
89
obj : object
90
The actual Python object
91
options : dict
92
Autodoc options
93
sig : str or None
94
Function signature string
95
retann : str or None
96
Return annotation string
97
98
Returns
99
-------
100
tuple of (str or None, str or None)
101
Modified (signature, return_annotation) or (None, None) for no change
102
"""
103
```
104
105
### Reference Processing
106
107
```python { .api }
108
def rename_references(app, what, name, obj, options, lines):
109
"""
110
Decorate references in docstrings for improved cross-linking.
111
112
Processes reference patterns to create proper Sphinx cross-references,
113
enabling automatic linking between documentation elements.
114
115
Parameters
116
----------
117
app : sphinx.application.Sphinx
118
Sphinx application instance
119
what : str
120
Type of object being documented
121
name : str
122
Fully qualified name of the object
123
obj : object
124
The actual Python object
125
options : dict
126
Autodoc options
127
lines : list of str
128
Docstring lines (modified in-place)
129
"""
130
131
def relabel_references(app, doc):
132
"""
133
Change reference labels to use object names instead of hashes.
134
135
Processes the document tree to replace generated reference labels
136
with more meaningful names based on the actual object names.
137
138
Parameters
139
----------
140
app : sphinx.application.Sphinx
141
Sphinx application instance
142
doc : docutils.nodes.document
143
Document node tree
144
"""
145
146
def clean_backrefs(app, doc, docname):
147
"""
148
Remove invalid back-references from the document.
149
150
Cleans up broken or invalid back-reference nodes that could
151
cause documentation build errors or warnings.
152
153
Parameters
154
----------
155
app : sphinx.application.Sphinx
156
Sphinx application instance
157
doc : docutils.nodes.document
158
Document node tree
159
docname : str
160
Name of the document being processed
161
"""
162
```
163
164
## Custom Domains
165
166
### Python Domain
167
168
```python { .api }
169
class NumpyPythonDomain(ManglingDomainBase, PythonDomain):
170
"""
171
Custom Python domain that handles NumPy-style docstring processing.
172
173
Extends Sphinx's built-in Python domain to provide NumPy-specific
174
functionality for docstring processing and cross-referencing.
175
176
Attributes
177
----------
178
name : str
179
Domain name ('npy')
180
"""
181
182
class ManglingDomainBase:
183
"""
184
Base class for mangling domains.
185
186
Provides common functionality for domains that need to process
187
and transform docstrings during the documentation build process.
188
"""
189
```
190
191
### C Domain
192
193
```python { .api }
194
class NumpyCDomain(ManglingDomainBase, CDomain):
195
"""
196
Custom C domain that handles NumPy-style docstring processing.
197
198
Extends Sphinx's built-in C domain to provide NumPy-specific
199
functionality for C API documentation with NumPy docstrings.
200
201
Attributes
202
----------
203
name : str
204
Domain name ('npy-c')
205
"""
206
```
207
208
## Configuration Management
209
210
### Configuration Updates
211
212
```python { .api }
213
def update_config(app, config=None):
214
"""
215
Update numpydoc configuration based on Sphinx config values.
216
217
Synchronizes numpydoc-specific configuration options with the
218
Sphinx configuration, applying defaults and validating values.
219
220
Parameters
221
----------
222
app : sphinx.application.Sphinx
223
Sphinx application instance
224
config : sphinx.config.Config or None
225
Sphinx configuration object (defaults to app.config)
226
"""
227
```
228
229
### Configuration Options
230
231
```python { .api }
232
# Configuration values registered with Sphinx
233
numpydoc_use_plots: bool = False
234
"""Enable plot directive processing in examples sections."""
235
236
numpydoc_show_class_members: bool = True
237
"""Show class members in generated documentation."""
238
239
numpydoc_show_inherited_class_members: bool = True
240
"""Show inherited class members in documentation."""
241
242
numpydoc_class_members_toctree: bool = True
243
"""Generate table of contents for class members."""
244
245
numpydoc_citation_re: str = "[\\w-]+(?:\\s+[\\w-]+)*"
246
"""Regular expression pattern for detecting citations."""
247
248
numpydoc_attributes_as_param_list: bool = True
249
"""Format class attributes as parameter lists."""
250
251
numpydoc_xref_param_type: bool = False
252
"""Enable cross-referencing of parameter types."""
253
254
numpydoc_xref_aliases: dict = {}
255
"""Custom type alias mappings for cross-references."""
256
257
numpydoc_xref_ignore: set = set()
258
"""Set of type names to ignore for cross-referencing."""
259
260
numpydoc_validation_checks: set = set()
261
"""Set of validation check codes to apply."""
262
263
numpydoc_validation_exclude: set = set()
264
"""Set of object patterns to exclude from validation."""
265
266
numpydoc_validation_overrides: dict = {}
267
"""Dictionary mapping object patterns to validation rule overrides."""
268
```
269
270
## Constants
271
272
```python { .api }
273
HASH_LEN: int = 12
274
"""Length for reference hash generation in cross-references."""
275
276
DEDUPLICATION_TAG: str = "<!-- numpydoc_validation -->"
277
"""HTML comment tag used to mark processed docstrings."""
278
```
279
280
## Usage Examples
281
282
### Basic Sphinx Extension Setup
283
284
```python
285
# conf.py
286
extensions = [
287
'sphinx.ext.autodoc',
288
'sphinx.ext.autosummary',
289
'numpydoc'
290
]
291
292
# Basic numpydoc configuration
293
numpydoc_use_plots = False
294
numpydoc_show_class_members = True
295
numpydoc_validation_checks = {'all'}
296
```
297
298
### Advanced Configuration
299
300
```python
301
# conf.py - Advanced numpydoc setup
302
numpydoc_xref_param_type = True
303
numpydoc_xref_aliases = {
304
'array_like': ':term:`array_like`',
305
'ndarray': 'numpy.ndarray',
306
'DataFrame': 'pandas.DataFrame'
307
}
308
309
numpydoc_validation_checks = {
310
'all', # Enable all validation checks
311
'GL08', # Check docstring formatting
312
'SS01', # Check summary sections
313
}
314
315
numpydoc_validation_exclude = {
316
r'\.tests\..*', # Exclude test modules
317
r'.*\._[^.]*$' # Exclude private modules
318
}
319
```
320
321
### Custom Domain Usage
322
323
```python
324
# Using custom domains in reStructuredText
325
.. npy:function:: my_function(x, y)
326
327
NumPy-style function with custom domain processing.
328
329
Parameters
330
----------
331
x : array_like
332
Input array
333
y : float
334
Scaling factor
335
```