0
# Utilities
1
2
Functions for discovering module objects, processing text, and handling integration with Sphinx's autosummary system. These utilities power the directive functionality and can be used programmatically for custom documentation workflows.
3
4
## Capabilities
5
6
### Module Object Discovery
7
8
Functions for finding and filtering public objects in Python modules, respecting `__all__` declarations and package boundaries.
9
10
```python { .api }
11
def find_mod_objs(modname: str, onlylocals: bool | list = False, sort: bool = False) -> tuple[list[str], list[str], list[object]]:
12
"""
13
Find all public objects in a module.
14
15
Parameters:
16
- modname: The name of the module to search
17
- onlylocals: If True, only include objects defined in this module.
18
If False, include imported objects. If a list, only include
19
objects from packages in the list. Ignored if module defines __all__
20
- sort: If True and module doesn't have __all__, sort objects alphabetically
21
22
Returns:
23
- tuple: Three lists:
24
- localnames: List of object names as they appear in the module
25
- fqnames: List of fully qualified names (e.g., 'package.module.Class')
26
- objs: List of the actual objects themselves
27
28
Notes:
29
- Respects __all__ if defined in the module
30
- Excludes private objects (names starting with '_')
31
- Does not include submodules or subpackages
32
"""
33
```
34
35
#### Usage Example
36
37
```python
38
from sphinx_automodapi.utils import find_mod_objs
39
40
# Find all public objects in a module
41
localnames, fqnames, objects = find_mod_objs('mypackage.utils')
42
for name, fqname, obj in zip(localnames, fqnames, objects):
43
print(f"{name} -> {fqname}: {type(obj).__name__}")
44
45
# Find only locally defined objects, sorted
46
localnames, fqnames, objects = find_mod_objs('mypackage.core', onlylocals=True, sort=True)
47
```
48
49
### Text Processing
50
51
Utilities for cleaning up generated documentation text to ensure proper formatting and whitespace handling.
52
53
```python { .api }
54
def cleanup_whitespace(text: str) -> str:
55
"""
56
Clean up whitespace in generated text.
57
58
- Ensures no more than two consecutive newlines
59
- Removes trailing whitespace from each line
60
- Adds a single trailing newline
61
62
Parameters:
63
- text: Input text to clean up
64
65
Returns:
66
- str: Cleaned text with normalized whitespace
67
"""
68
```
69
70
#### Usage Example
71
72
```python
73
from sphinx_automodapi.utils import cleanup_whitespace
74
75
# Clean up generated documentation text
76
raw_text = "Some text \n\n\n\nMore text \n"
77
clean_text = cleanup_whitespace(raw_text)
78
# Result: "Some text\n\nMore text\n"
79
```
80
81
### Autosummary Integration
82
83
Functions for integrating with Sphinx's autosummary system, handling the discovery and processing of autosummary directives within automodsumm contexts.
84
85
```python { .api }
86
def find_autosummary_in_lines_for_automodsumm(lines: list[str], module: str = None,
87
filename: str = None) -> list:
88
"""
89
Find autosummary directives in lines for automodsumm processing.
90
91
Modified version of sphinx.ext.autosummary's find_autosummary_in_docstring
92
that works with automodsumm directive processing.
93
94
Parameters:
95
- lines: List of lines to search for autosummary directives
96
- module: Module name context for resolving references
97
- filename: Filename context for error reporting
98
99
Returns:
100
- list: List of discovered autosummary items
101
"""
102
```
103
104
#### Usage Example
105
106
```python
107
from sphinx_automodapi.utils import find_autosummary_in_lines_for_automodsumm
108
109
# Process lines containing autosummary directives
110
lines = [
111
".. autosummary::",
112
" :toctree: generated/",
113
"",
114
" function1",
115
" Class1"
116
]
117
118
autosummary_items = find_autosummary_in_lines_for_automodsumm(
119
lines, module='mypackage.core'
120
)
121
```
122
123
## Document Generation Functions
124
125
Higher-level functions for generating documentation content from automodsumm directives.
126
127
```python { .api }
128
def automodsumm_to_autosummary_lines(fn: str, app: Sphinx) -> list[str]:
129
"""
130
Convert automodsumm file to autosummary lines.
131
132
Parameters:
133
- fn: Filename containing automodsumm directives
134
- app: Sphinx application instance
135
136
Returns:
137
- list: Lines converted to autosummary format
138
"""
139
140
def generate_automodsumm_docs(lines: list[str], srcfn: str, app: Sphinx = None,
141
suffix: str = '.rst', base_path: str = None,
142
builder=None, template_dir: str = None,
143
inherited_members: bool = False,
144
included_members: tuple = ('__init__', '__call__'),
145
properties_are_attributes: bool = True, **kwargs) -> None:
146
"""
147
Generate documentation from automodsumm lines.
148
149
Parameters:
150
- lines: Lines containing automodsumm directives
151
- srcfn: Source filename
152
- app: Sphinx application instance
153
- suffix: File suffix for generated files
154
- base_path: Base path for generated files
155
- builder: Sphinx builder instance
156
- template_dir: Directory containing custom templates
157
- inherited_members: Include inherited class members
158
- included_members: Special method names to include
159
- properties_are_attributes: Treat properties as attributes
160
- **kwargs: Additional options passed to generation
161
"""
162
163
def process_automodsumm_generation(app: Sphinx) -> None:
164
"""
165
Process automodsumm generation for all documents.
166
167
Connected to Sphinx's 'builder-inited' event to generate documentation
168
for all automodsumm directives found in the project.
169
170
Parameters:
171
- app: Sphinx application instance
172
"""
173
```
174
175
## Internal Constants
176
177
```python { .api }
178
# Text processing constants
179
SPACE_NEWLINE: str = ' \n'
180
SINGLE_NEWLINE: str = '\n'
181
DOUBLE_NEWLINE: str = '\n\n'
182
TRIPLE_NEWLINE: str = '\n\n\n'
183
```
184
185
## Implementation Notes
186
187
### Module Object Discovery Logic
188
189
The `find_mod_objs` function implements sophisticated logic for determining which objects to include:
190
191
1. **__all__ handling**: If a module defines `__all__`, only objects listed there are included
192
2. **Local filtering**: When `onlylocals=True`, only objects defined in the target module are included
193
3. **Package filtering**: When `onlylocals` is a list, only objects from specified packages are included
194
4. **Private filtering**: Objects with names starting with underscore are excluded
195
5. **Sorting**: Objects can be sorted alphabetically when `__all__` is not defined
196
197
### Text Normalization
198
199
The `cleanup_whitespace` function ensures consistent formatting by:
200
201
1. Removing trailing whitespace from each line
202
2. Limiting consecutive newlines to maximum of two
203
3. Ensuring the text ends with exactly one newline
204
4. Preserving overall text structure and content
205
206
This normalization is essential for generating clean, consistent documentation output that integrates well with Sphinx's processing pipeline.