0
# Core Analysis
1
2
AST-based analysis engine that traverses Python code to validate docstring compliance against function signatures, with support for all docstring styles and comprehensive validation rules.
3
4
## Capabilities
5
6
### Visitor Class
7
8
The main AST visitor that performs comprehensive docstring analysis by traversing Python source code and validating docstring compliance.
9
10
```python { .api }
11
class Visitor(ast.NodeVisitor):
12
"""
13
AST visitor for analyzing Python docstrings against function signatures.
14
15
Traverses Python AST nodes to validate docstring compliance with function
16
signatures, supporting numpy, google, and sphinx docstring styles with
17
comprehensive validation rules.
18
"""
19
20
def __init__(
21
self,
22
style: str = 'numpy',
23
argTypeHintsInSignature: bool = True,
24
argTypeHintsInDocstring: bool = True,
25
checkArgOrder: bool = True,
26
skipCheckingShortDocstrings: bool = True,
27
skipCheckingRaises: bool = False,
28
allowInitDocstring: bool = False,
29
checkReturnTypes: bool = True,
30
checkYieldTypes: bool = True,
31
ignoreUnderscoreArgs: bool = True,
32
ignorePrivateArgs: bool = False,
33
checkClassAttributes: bool = True,
34
shouldDocumentPrivateClassAttributes: bool = False,
35
treatPropertyMethodsAsClassAttributes: bool = False,
36
onlyAttrsWithClassVarAreTreatedAsClassAttrs: bool = False,
37
requireReturnSectionWhenReturningNothing: bool = False,
38
requireYieldSectionWhenYieldingNothing: bool = False,
39
shouldDocumentStarArguments: bool = True,
40
shouldDeclareAssertErrorIfAssertStatementExists: bool = False,
41
checkStyleMismatch: bool = False,
42
checkArgDefaults: bool = False,
43
) -> None:
44
"""
45
Initialize visitor with validation configuration.
46
47
Parameters:
48
- style: Docstring style to validate ('numpy', 'google', 'sphinx')
49
- argTypeHintsInSignature: Require type hints in function signatures
50
- argTypeHintsInDocstring: Require type hints in docstring arguments
51
- checkArgOrder: Validate argument order matches between signature and docstring
52
- skipCheckingShortDocstrings: Skip validation for summary-only docstrings
53
- skipCheckingRaises: Skip validation of raises sections against raise statements
54
- allowInitDocstring: Allow both __init__ and class to have docstrings
55
- checkReturnTypes: Validate return types match between signature and docstring
56
- checkYieldTypes: Validate yield types match between signature and docstring
57
- ignoreUnderscoreArgs: Ignore underscore arguments (_, __, etc.) in validation
58
- ignorePrivateArgs: Ignore private arguments (leading underscore) in validation
59
- checkClassAttributes: Validate class attributes against class docstring
60
- shouldDocumentPrivateClassAttributes: Require private class attributes in docstring
61
- treatPropertyMethodsAsClassAttributes: Treat @property methods as class attributes
62
- onlyAttrsWithClassVarAreTreatedAsClassAttrs: Only ClassVar annotations as class attrs
63
- requireReturnSectionWhenReturningNothing: Require return section for None returns
64
- requireYieldSectionWhenYieldingNothing: Require yields section for None yields
65
- shouldDocumentStarArguments: Require *args/**kwargs in docstrings
66
- shouldDeclareAssertErrorIfAssertStatementExists: Declare AssertionError for assert statements
67
- checkStyleMismatch: Validate consistent style within docstrings
68
- checkArgDefaults: Validate default values in docstring type hints match signature
69
"""
70
71
def visit(self, node: ast.AST) -> None:
72
"""
73
Visit AST node and perform docstring analysis.
74
75
Traverses the AST and analyzes function definitions, class definitions,
76
and method definitions for docstring compliance.
77
78
Parameters:
79
- node: AST node to visit and analyze
80
"""
81
82
@property
83
def violations(self) -> list[Violation]:
84
"""
85
Get list of violations found during analysis.
86
87
Returns:
88
list[Violation]: All violations detected during AST traversal
89
"""
90
```
91
92
### AST Node Visitors
93
94
The visitor implements specific methods for different AST node types to perform targeted analysis.
95
96
```python { .api }
97
def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
98
"""
99
Visit function definition node.
100
101
Analyzes function docstrings against signatures, including:
102
- Argument validation
103
- Return type validation
104
- Yield type validation
105
- Raises section validation
106
- Type hint consistency
107
108
Parameters:
109
- node: Function definition AST node
110
"""
111
112
def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:
113
"""
114
Visit async function definition node.
115
116
Analyzes async function docstrings with same validation as regular functions,
117
with special handling for async-specific patterns.
118
119
Parameters:
120
- node: Async function definition AST node
121
"""
122
123
def visit_ClassDef(self, node: ast.ClassDef) -> None:
124
"""
125
Visit class definition node.
126
127
Analyzes class docstrings and class attributes, including:
128
- Class attribute validation against docstring
129
- __init__ method docstring validation
130
- Property method handling
131
- Private attribute documentation rules
132
133
Parameters:
134
- node: Class definition AST node
135
"""
136
```
137
138
## Usage Examples
139
140
### Basic Visitor Usage
141
142
```python
143
import ast
144
from pydoclint.visitor import Visitor
145
146
# Parse Python source code
147
source = '''
148
def example_function(x: int, y: str = "default") -> bool:
149
"""Example function.
150
151
Parameters
152
----------
153
x : int
154
First parameter
155
y : str
156
Second parameter
157
158
Returns
159
-------
160
bool
161
Whether operation succeeded
162
"""
163
return True
164
'''
165
166
tree = ast.parse(source)
167
visitor = Visitor(style="numpy")
168
visitor.visit(tree)
169
170
# Check for violations
171
for violation in visitor.violations:
172
print(f"Line {violation.line}: {violation.fullErrorCode} - {violation.msg}")
173
```
174
175
### Advanced Configuration
176
177
```python
178
# Strict validation with all checks enabled
179
visitor = Visitor(
180
style="google",
181
checkArgOrder=True,
182
checkReturnTypes=True,
183
checkYieldTypes=True,
184
checkClassAttributes=True,
185
shouldDocumentStarArguments=True,
186
checkStyleMismatch=True,
187
requireReturnSectionWhenReturningNothing=True
188
)
189
190
# Lenient validation for legacy code
191
visitor = Visitor(
192
style="numpy",
193
skipCheckingShortDocstrings=True,
194
skipCheckingRaises=True,
195
ignoreUnderscoreArgs=True,
196
ignorePrivateArgs=True,
197
allowInitDocstring=True
198
)
199
```
200
201
### Class Attribute Validation
202
203
```python
204
source = '''
205
class ExampleClass:
206
"""Example class with attributes.
207
208
Attributes
209
----------
210
public_attr : str
211
Public class attribute
212
_private_attr : int
213
Private class attribute
214
"""
215
216
public_attr: str = "default"
217
_private_attr: int = 42
218
219
def __init__(self):
220
"""Initialize instance."""
221
pass
222
'''
223
224
tree = ast.parse(source)
225
visitor = Visitor(
226
style="numpy",
227
checkClassAttributes=True,
228
shouldDocumentPrivateClassAttributes=True
229
)
230
visitor.visit(tree)
231
232
# Will validate that documented attributes match actual class attributes
233
```
234
235
### Style-Specific Analysis
236
237
```python
238
# Google style validation
239
google_visitor = Visitor(style="google")
240
241
# Sphinx style validation
242
sphinx_visitor = Visitor(style="sphinx")
243
244
# Style mismatch detection
245
mismatch_visitor = Visitor(
246
style="numpy",
247
checkStyleMismatch=True # Will flag docstrings that don't match numpy style
248
)
249
```
250
251
### Generator and Async Function Analysis
252
253
```python
254
source = '''
255
async def async_generator(items: list[str]) -> AsyncGenerator[str, None]:
256
"""Process items asynchronously.
257
258
Parameters
259
----------
260
items : list[str]
261
Items to process
262
263
Yields
264
------
265
str
266
Processed item
267
"""
268
for item in items:
269
yield f"processed: {item}"
270
'''
271
272
tree = ast.parse(source)
273
visitor = Visitor(
274
style="numpy",
275
checkYieldTypes=True,
276
requireYieldSectionWhenYieldingNothing=False
277
)
278
visitor.visit(tree)
279
280
# Will validate yield type consistency and yields section requirements
281
```