Coverage for pydantic / _internal / _docs_extraction.py: 94.51%

69 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-11-21 11:56 +0000

1"""Utilities related to attribute docstring extraction.""" 

2 

3from __future__ import annotations 1adpghibeqjklscfrmno

4 

5import ast 1adpghibeqjklscfrmno

6import inspect 1adpghibeqjklscfrmno

7import sys 1adpghibeqjklscfrmno

8import textwrap 1adpghibeqjklscfrmno

9from typing import Any 1adpghibeqjklscfrmno

10 

11 

12class DocstringVisitor(ast.NodeVisitor): 1adpghibeqjklscfrmno

13 def __init__(self) -> None: 1adpghibeqjklscfrmno

14 super().__init__() 1adpghibeqjklcfrmno

15 

16 self.target: str | None = None 1adpghibeqjklcfrmno

17 self.attrs: dict[str, str] = {} 1adpghibeqjklcfrmno

18 self.previous_node_type: type[ast.AST] | None = None 1adpghibeqjklcfrmno

19 

20 def visit(self, node: ast.AST) -> Any: 1adpghibeqjklscfrmno

21 node_result = super().visit(node) 1adpghibeqjklcfrmno

22 self.previous_node_type = type(node) 1adpghibeqjklcfrmno

23 return node_result 1adpghibeqjklcfrmno

24 

25 def visit_AnnAssign(self, node: ast.AnnAssign) -> Any: 1adpghibeqjklscfrmno

26 if isinstance(node.target, ast.Name): 26 ↛ exitline 26 didn't return from function 'visit_AnnAssign' because the condition on line 26 was always true1adpghibeqjklcfrmno

27 self.target = node.target.id 1adpghibeqjklcfrmno

28 

29 def visit_Expr(self, node: ast.Expr) -> Any: 1adpghibeqjklscfrmno

30 if ( 1aghibjklcmno

31 isinstance(node.value, ast.Constant) 

32 and isinstance(node.value.value, str) 

33 and self.previous_node_type is ast.AnnAssign 

34 ): 

35 docstring = inspect.cleandoc(node.value.value) 1adpghibeqjklcfrmno

36 if self.target: 36 ↛ 38line 36 didn't jump to line 38 because the condition on line 36 was always true1adpghibeqjklcfrmno

37 self.attrs[self.target] = docstring 1adpghibeqjklcfrmno

38 self.target = None 1adpghibeqjklcfrmno

39 

40 # Don't look into nested classes and functions, as their attributes don't belong to the inspected class: 

41 def visit_ClassDef(self, node: ast.ClassDef) -> Any: 1adpghibeqjklscfrmno

42 pass 1adpghibeqjklcfrmno

43 

44 def visit_FunctionDef(self, node: ast.FunctionDef) -> Any: 1adpghibeqjklscfrmno

45 pass 1adpghibeqjklcfrmno

46 

47 def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> Any: 1adpghibeqjklscfrmno

48 pass 

49 

50 

51def _dedent_source_lines(source: list[str]) -> str: 1adpghibeqjklscfrmno

52 # Required for nested class definitions, e.g. in a function block 

53 dedent_source = textwrap.dedent(''.join(source)) 1adpghibeqjklcfrmno

54 if dedent_source.startswith((' ', '\t')): 1adpghibeqjklcfrmno

55 # We are in the case where there's a dedented (usually multiline) string 

56 # at a lower indentation level than the class itself. We wrap our class 

57 # in a function as a workaround. 

58 dedent_source = f'def dedent_workaround():\n{dedent_source}' 1adpghibeqjklcfrmno

59 return dedent_source 1adpghibeqjklcfrmno

60 

61 

62def _extract_source_from_frame(cls: type[Any]) -> list[str] | None: 1adpghibeqjklscfrmno

63 frame = inspect.currentframe() 1adbecf

64 

65 while frame: 1adbecf

66 if inspect.getmodule(frame) is inspect.getmodule(cls): 1adbecf

67 lnum = frame.f_lineno 1adbecf

68 try: 1adbecf

69 lines, _ = inspect.findsource(frame) 1adbecf

70 except OSError: # pragma: no cover 

71 # Source can't be retrieved (maybe because running in an interactive terminal), 

72 # we don't want to error here. 

73 pass 

74 else: 

75 block_lines = inspect.getblock(lines[lnum - 1 :]) 1adbecf

76 dedent_source = _dedent_source_lines(block_lines) 1adbecf

77 try: 1adbecf

78 block_tree = ast.parse(dedent_source) 1adbecf

79 except SyntaxError: 

80 pass 

81 else: 

82 stmt = block_tree.body[0] 1adbecf

83 if isinstance(stmt, ast.FunctionDef) and stmt.name == 'dedent_workaround': 1adbecf

84 # `_dedent_source_lines` wrapped the class around the workaround function 

85 stmt = stmt.body[0] 1adbecf

86 if isinstance(stmt, ast.ClassDef) and stmt.name == cls.__name__: 1adbecf

87 return block_lines 1adbecf

88 

89 frame = frame.f_back 1adbecf

90 

91 

92def extract_docstrings_from_cls(cls: type[Any], use_inspect: bool = False) -> dict[str, str]: 1adpghibeqjklscfrmno

93 """Map model attributes and their corresponding docstring. 

94 

95 Args: 

96 cls: The class of the Pydantic model to inspect. 

97 use_inspect: Whether to skip usage of frames to find the object and use 

98 the `inspect` module instead. 

99 

100 Returns: 

101 A mapping containing attribute names and their corresponding docstring. 

102 """ 

103 if use_inspect or sys.version_info >= (3, 13): 1adpghibeqjklcfrmno

104 # On Python < 3.13, `inspect.getsourcelines()` might not work as expected 

105 # if two classes have the same name in the same source file. 

106 # On Python 3.13+, it will use the new `__firstlineno__` class attribute, 

107 # making it way more robust. 

108 try: 1adpghibeqjklcfrmno

109 source, _ = inspect.getsourcelines(cls) 1adpghibeqjklcfrmno

110 except (OSError, TypeError): # pragma: no cover 1pghiqjklrmno

111 return {} 1pghiqjklrmno

112 else: 

113 # TODO remove this implementation when we drop support for Python 3.12: 

114 source = _extract_source_from_frame(cls) 1adbecf

115 

116 if not source: 1adpghibeqjklcfrmno

117 return {} 1adbecf

118 

119 dedent_source = _dedent_source_lines(source) 1adpghibeqjklcfrmno

120 

121 stmt = ast.parse(dedent_source).body[0] 1adpghibeqjklcfrmno

122 if isinstance(stmt, ast.FunctionDef) and stmt.name == 'dedent_workaround': 1adpghibeqjklcfrmno

123 # `_dedent_source_lines()` wrapped the class around the workaround function 

124 stmt = stmt.body[0] 1adpghibeqjklcfrmno

125 

126 visitor = DocstringVisitor() 1adpghibeqjklcfrmno

127 visitor.generic_visit(stmt) 1adpghibeqjklcfrmno

128 return visitor.attrs 1adpghibeqjklcfrmno