-
Notifications
You must be signed in to change notification settings - Fork 91
Expand file tree
/
Copy pathdocstrings.py
More file actions
538 lines (407 loc) · 16.8 KB
/
docstrings.py
File metadata and controls
538 lines (407 loc) · 16.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
"""
This module implements classes and methods for **BASIC** parsing of docstrings, to
obtain some information, such as parameters descriptions, that can be used for
OpenAPI Documentation. The framework also provides the possibility to control the docs
configuration directly: if simple parsing doesn't work, the user should use the @docs
decorator.
These are not meant to be a complete parsing solution, that would be worth a whole
library by itself!
See
* https://www.neoteroi.dev/blacksheep/openapi/
* http://epydoc.sourceforge.net/manual-epytext.html#the-epytext-markup-language
* https://github.com/google/styleguide/blob/gh-pages/pyguide.md
* https://numpydoc.readthedocs.io/en/latest/format.html
* https://www.sphinx-doc.org/en/master/
* tests/test_openapi_docstrings.py
"""
import re
import sys
import warnings
from abc import ABC, abstractmethod
from dataclasses import dataclass
from datetime import date, datetime
from textwrap import dedent
from typing import Any, Sequence, Type
from uuid import UUID
from weakref import WeakKeyDictionary
from .common import ParameterInfo
@dataclass
class FunctionInfo:
summary: str
description: str
@dataclass
class ReturnInfo:
return_type: Any
return_description: str
@dataclass
class DocstringInfo:
summary: str
description: str
parameters: dict[str, ParameterInfo]
return_type: Type | None = None
return_description: str | None = None
class DocstringDialect(ABC):
@abstractmethod
def is_match(self, docstring: str) -> bool:
"""
Returns a value indicating whether the docstring
seems to be written in this format.
"""
@abstractmethod
def parse_docstring(self, docstring: str) -> DocstringInfo:
"""
Parses the docstring into an instance of DocstringInfo
"""
TYPE_REPRS = {
"bool": bool,
"boolean": bool,
"number": float,
"integer": int,
"int": int,
"float": float,
"date": date,
"datetime": datetime,
"uuid": UUID,
"guid": UUID,
"string": str,
"str": str,
}
_array_rx = re.compile(
r"(?P<type_name1>[a-zA-Z]+)\[\]|"
r"([lL]ist|[aA]rray|[sS]equence)\[(?P<type_name2>[a-zA-Z]+)\]"
)
def type_repr_to_type(type_repr: str) -> Type | None:
array_match = _array_rx.match(type_repr)
if array_match:
type_repr = array_match.group("type_name1") or array_match.group("type_name2")
if type_repr in TYPE_REPRS:
value_type = TYPE_REPRS[type_repr]
return list[value_type]
if type_repr in TYPE_REPRS:
return TYPE_REPRS[type_repr]
return None
def collapse(value: str) -> str:
if not value:
return value
return " ".join(dedent(value).split())
def handle_type_repr(parameter_info: ParameterInfo, type_repr: str) -> None:
if not type_repr:
return
if " or None" in type_repr or type_repr.endswith("?"):
parameter_info.required = False
type_repr = type_repr.replace(" or None", "").replace("?", "")
for value in {", optional", "; optional"}:
if value in type_repr:
parameter_info.required = False
type_repr = type_repr.replace(value, "")
parameter_info.value_type = type_repr_to_type(type_repr)
if parameter_info.value_type is None:
if parameter_info.description:
parameter_info.description = parameter_info.description + f" ({type_repr})"
else:
parameter_info.description = type_repr
def get_summary(description: str) -> str:
if "\n\n" in description:
return description.split("\n\n")[0]
else:
return description
@dataclass
class PatternsDocstringDialectOptions:
description_rx: re.Pattern
return_rx: re.Pattern
return_type_rx: re.Pattern
param_rx: re.Pattern
param_type_rx: re.Pattern
class PatternsDocstringDialect(DocstringDialect):
def __init__(self, options: PatternsDocstringDialectOptions) -> None:
super().__init__()
self._options = options
def get_parameters_info(self, docstring: str) -> dict[str, ParameterInfo]:
parameters: dict[str, ParameterInfo] = {}
types: dict[str, Any] = {}
for m in self._options.param_rx.finditer(docstring):
param_name = m.group("param_name").strip()
if " " in param_name:
# TODO: support the same in Googledoc and Numpydoc
# handle optional type in the param_name, like:
# @param int foo:
# @param int or None foo:
(*type_parts, name) = param_name.split(" ")
types[name] = " ".join(type_parts)
param_name = name
parameters[param_name] = ParameterInfo(
description=collapse(m.group("param_desc"))
)
for m in self._options.param_type_rx.finditer(docstring):
types[m.group("param_name").strip()] = m.group("type_repr").strip()
for key, value in types.items():
if key in parameters:
parameter_info = parameters[key]
handle_type_repr(parameter_info, value)
return parameters
def parse_docstring(self, docstring: str) -> DocstringInfo:
return_description = None
docstring = dedent(docstring).strip("\n")
m = self._options.return_rx.search(docstring)
if m:
return_description = m.group("description")
m = self._options.return_type_rx.search(docstring)
if m:
return_type = type_repr_to_type(m.group("type_repr").strip())
else:
return_type = None
description_m = self._options.description_rx.match(docstring)
if description_m:
description = description_m.group("description").strip()
else: # pragma: no cover
# this is not expected
description = ""
return DocstringInfo(
summary=collapse(get_summary(description)),
description=collapse(description),
parameters=self.get_parameters_info(docstring),
return_type=return_type,
return_description=(
collapse(return_description) if return_description else None
),
)
@dataclass
class SectionFragment:
header: str
value: str
def add(self, part: str) -> None:
self.value = (self.value or "") + part
def get_indentation(line: str) -> int:
m = re.match(r"^([\s\t]+)", line)
if not m:
return -1
return len(m.group(1))
class IndentDocstringDialect(DocstringDialect):
def is_section_separator(self, line: str) -> bool:
return False
def get_section(self, docstring: str, section_name: str) -> list[SectionFragment]:
fragments: list[SectionFragment] = []
section_started = False
current_indentation = -1 # indentation of the current section
open_fragment: SectionFragment | None = None
for line in docstring.splitlines():
if line == "":
continue
if self.is_section_separator(line) and fragments:
return fragments
if re.match(r"^[-\s\t]+$", line):
continue
line_indentation = get_indentation(line)
if line_indentation < current_indentation:
break
if section_started:
if open_fragment is None:
open_fragment = SectionFragment(line, "")
current_indentation = get_indentation(line)
else:
if line_indentation > current_indentation:
open_fragment.add(line)
else:
fragments.append(open_fragment)
open_fragment = SectionFragment(line, "")
current_indentation = get_indentation(line)
elif line == section_name or line == f"{section_name}:":
section_started = True
if open_fragment is not None and open_fragment not in fragments:
fragments.append(open_fragment)
return fragments
class EpytextDialect(PatternsDocstringDialect):
def __init__(self, options: PatternsDocstringDialectOptions | None = None) -> None:
super().__init__(options or self._default_options)
_default_options = PatternsDocstringDialectOptions(
description_rx=re.compile(r"^(?P<description>[^\@]+)"),
return_rx=re.compile(r"@return:\s*(?P<description>[^\@]+)"),
return_type_rx=re.compile(r"@rtype:\s*(?P<type_repr>[^\@]+)"),
param_rx=re.compile(
r"@param\s(?P<param_name>[^\:]+):\s*(?P<param_desc>[^\@]+)"
),
param_type_rx=re.compile(
r"@type\s*(?P<param_name>[^\:]+):\s*(?P<type_repr>[^\@]+)"
),
)
def is_match(self, docstring: str) -> bool:
return "@param" in docstring
class ReStructuredTextDialect(PatternsDocstringDialect):
def __init__(self, options: PatternsDocstringDialectOptions | None = None) -> None:
super().__init__(options or self._default_options)
_default_options = PatternsDocstringDialectOptions(
description_rx=re.compile(r"^(?P<description>[^\:]+)"),
return_rx=re.compile(r":return:\s*(?P<description>[^\:]+)"),
return_type_rx=re.compile(r":rtype:\s*(?P<type_repr>[^\:]+)"),
param_rx=re.compile(
r":param\s(?P<param_name>[^\:]+):\s*(?P<param_desc>[^\:]+)"
),
param_type_rx=re.compile(
r":type\s*(?P<param_name>[^\:]+):\s*(?P<type_repr>[^\:]+)"
),
)
def is_match(self, docstring: str) -> bool:
return ":param" in docstring
class NumpydocDialect(IndentDocstringDialect):
def is_match(self, docstring: str) -> bool:
return (
"Parameters" in docstring or "Params" in docstring
) and "--" in docstring
_sections = {"Parameters", "Params", "Returns", "Return", "Raises"}
def is_section_separator(self, line: str) -> bool:
return re.match(r"^[-\s\t]+$", line) is not None
def get_description(self, docstring: str) -> FunctionInfo:
lines: list[str] = []
for line in docstring.splitlines():
if self.is_section_separator(line.strip()):
lines = lines[:-1]
break
if line.strip() in self._sections:
break
lines.append(line)
description = "\n".join(lines)
return FunctionInfo(summary=get_summary(description), description=description)
def get_return_info(self, docstring: str) -> ReturnInfo | None:
section = self.get_section(docstring, "Returns") or self.get_section(
docstring, "Return"
)
if not section:
return None
fragment = section[0]
return ReturnInfo(
return_type=type_repr_to_type(fragment.header),
return_description=collapse(fragment.value),
)
def get_parameters_info(self, docstring: str) -> dict[str, ParameterInfo]:
parameters: dict[str, ParameterInfo] = {}
parameters_section = self.get_section(
docstring, "Parameters"
) or self.get_section(docstring, "Params")
for fragment in parameters_section:
if ":" not in fragment.header:
warnings.warn(
f"Invalid parameter definition in docstring: {fragment.header}"
)
continue
name_part, type_part = re.split(r"\s*:\s*", fragment.header)
# TODO: support name_part containing type information, e.g.
# param1 int: some description!
parameter_info = ParameterInfo(
description=collapse(fragment.value),
)
parameters[name_part.strip()] = parameter_info
handle_type_repr(parameter_info, type_part)
return parameters
def parse_docstring(self, docstring: str) -> DocstringInfo:
docstring = dedent(docstring)
info = self.get_description(docstring)
return_info = self.get_return_info(docstring)
return DocstringInfo(
summary=collapse(info.summary),
description=collapse(info.description),
parameters=self.get_parameters_info(docstring),
return_type=return_info.return_type if return_info else None,
return_description=(
collapse(return_info.return_description) if return_info else None
),
)
class GoogleDocDialect(IndentDocstringDialect):
def is_match(self, docstring: str) -> bool:
return re.search(r"^([\s\t]*Args:?)", docstring, re.M) is not None
_sections = {"Args", "Returns", "Raises"}
def is_section_start(self, line: str) -> bool:
return line.strip(" :") in self._sections
def get_description(self, docstring: str) -> FunctionInfo:
lines: list[str] = []
for line in docstring.splitlines():
if self.is_section_start(line):
lines = lines[:-1]
break
lines.append(line)
description = "\n".join(lines)
return FunctionInfo(summary=get_summary(description), description=description)
def get_parameters_info(self, docstring: str) -> dict[str, ParameterInfo]:
parameters: dict[str, ParameterInfo] = {}
parameters_section = self.get_section(docstring, "Args")
for fragment in parameters_section:
if ":" not in fragment.header:
warnings.warn(
"Invalid parameter definition in docstring: "
f"{fragment.header.strip()}"
)
continue
name_part, header_part = re.split(r"\s*:\s*", fragment.header)
description = header_part + " " + fragment.value
# TODO: support name_part containing type information, e.g.
# param1 int: some description!
parameters[name_part.strip()] = ParameterInfo(
description=collapse(description),
)
# Note: the type is not currently supported in Google docstrings;
# the user can anyway specify the arguments types using type annotations,
# which is a better way in any case.
return parameters
def get_return_info(self, docstring: str) -> ReturnInfo | None:
section = self.get_section(docstring, "Returns")
if not section:
return None
description = " ".join(
fragment.header + " " + fragment.value for fragment in section
)
return ReturnInfo(
return_type=None,
return_description=collapse(description),
)
def parse_docstring(self, docstring: str) -> DocstringInfo:
docstring = dedent(docstring)
info = self.get_description(docstring)
return_info = self.get_return_info(docstring)
return DocstringInfo(
summary=collapse(info.summary),
description=collapse(info.description),
parameters=self.get_parameters_info(docstring),
return_type=return_info.return_type if return_info else None,
return_description=(
collapse(return_info.return_description) if return_info else None
),
)
default_dialects = [
EpytextDialect(),
ReStructuredTextDialect(),
NumpydocDialect(),
GoogleDocDialect(),
]
def parse_docstring(
docstring: str,
dialects: Sequence[DocstringDialect] | None = None,
) -> DocstringInfo:
assert bool(docstring), "a docstring is required"
if not dialects:
dialects = default_dialects
for dialect in dialects:
if dialect.is_match(docstring):
return dialect.parse_docstring(docstring)
return dialects[0].parse_docstring(docstring)
_handlers_docstring_info = WeakKeyDictionary()
_optimize_warning_issued = False
def get_handler_docstring_info(handler) -> DocstringInfo:
global _optimize_warning_issued
if handler not in _handlers_docstring_info:
docs = handler.__doc__
if docs:
docstring_info = parse_docstring(docs)
else:
if sys.flags.optimize >= 2 and not _optimize_warning_issued:
_optimize_warning_issued = True
warnings.warn(
"Python is running with PYTHONOPTIMIZE=2 (or -OO), so docstrings "
"are not available and cannot be used to enrich OpenAPI "
"Documentation. Consider baking the OpenAPI spec to a file before "
"deploying: call docs.save_spec() after starting the application "
"once without -OO, then set APP_SPEC_FILE to the saved path so "
"that BlackSheep loads it at runtime instead of regenerating it.",
stacklevel=2,
)
docstring_info = None
_handlers_docstring_info[handler] = docstring_info
return _handlers_docstring_info[handler]