Coverage for pydantic/_internal/_repr.py: 100.00%

70 statements  

« prev     ^ index     » next       coverage.py v7.9.1, created at 2025-06-14 08:39 +0000

1"""Tools to provide pretty/human-readable display of objects.""" 

2 

3from __future__ import annotations as _annotations 1abhijklmnopcqderstuvwxyzJfgABCDEFGHI

4 

5import types 1abhijklmnopcqderstuvwxyzJfgABCDEFGHI

6import typing 1abhijklmnopcqderstuvwxyzJfgABCDEFGHI

7from typing import Any 1abhijklmnopcqderstuvwxyzJfgABCDEFGHI

8 

9import typing_extensions 1abhijklmnopcqderstuvwxyzJfgABCDEFGHI

10from typing_inspection import typing_objects 1abhijklmnopcqderstuvwxyzJfgABCDEFGHI

11from typing_inspection.introspection import is_union_origin 1abhijklmnopcqderstuvwxyzJfgABCDEFGHI

12 

13from . import _typing_extra 1abhijklmnopcqderstuvwxyzJfgABCDEFGHI

14 

15if typing.TYPE_CHECKING: 1abhijklmnopcqderstuvwxyzJfgABCDEFGHI

16 ReprArgs: typing_extensions.TypeAlias = 'typing.Iterable[tuple[str | None, Any]]' 

17 RichReprResult: typing_extensions.TypeAlias = ( 

18 'typing.Iterable[Any | tuple[Any] | tuple[str, Any] | tuple[str, Any, Any]]' 

19 ) 

20 

21 

22class PlainRepr(str): 1abhijklmnopcqderstuvwxyzJfgABCDEFGHI

23 """String class where repr doesn't include quotes. Useful with Representation when you want to return a string 

24 representation of something that is valid (or pseudo-valid) python. 

25 """ 

26 

27 def __repr__(self) -> str: 1abhijklmnopcqderstuvwxyzJfgABCDEFGHI

28 return str(self) 1abhijklmnopcqderstuvwxyzfgABCDEFGHI

29 

30 

31class Representation: 1abhijklmnopcqderstuvwxyzJfgABCDEFGHI

32 # Mixin to provide `__str__`, `__repr__`, and `__pretty__` and `__rich_repr__` methods. 

33 # `__pretty__` is used by [devtools](https://python-devtools.helpmanual.io/). 

34 # `__rich_repr__` is used by [rich](https://rich.readthedocs.io/en/stable/pretty.html). 

35 # (this is not a docstring to avoid adding a docstring to classes which inherit from Representation) 

36 

37 # we don't want to use a type annotation here as it can break get_type_hints 

38 __slots__ = () # type: typing.Collection[str] 1abhijklmnopcqderstuvwxyzJfgABCDEFGHI

39 

40 def __repr_args__(self) -> ReprArgs: 1abhijklmnopcqderstuvwxyzJfgABCDEFGHI

41 """Returns the attributes to show in __str__, __repr__, and __pretty__ this is generally overridden. 

42 

43 Can either return: 

44 * name - value pairs, e.g.: `[('foo_name', 'foo'), ('bar_name', ['b', 'a', 'r'])]` 

45 * or, just values, e.g.: `[(None, 'foo'), (None, ['b', 'a', 'r'])]` 

46 """ 

47 attrs_names = self.__slots__ 1abhijklmnopcqderstuvwxyzfgABCDEFGHI

48 if not attrs_names and hasattr(self, '__dict__'): 1abhijklmnopcqderstuvwxyzfgABCDEFGHI

49 attrs_names = self.__dict__.keys() 1abhijklmnopcqderstuvwxyzfgABCDEFGHI

50 attrs = ((s, getattr(self, s)) for s in attrs_names) 1abhijklmnopcqderstuvwxyzfgABCDEFGHI

51 return [(a, v if v is not self else self.__repr_recursion__(v)) for a, v in attrs if v is not None] 1abhijklmnopcqderstuvwxyzfgABCDEFGHI

52 

53 def __repr_name__(self) -> str: 1abhijklmnopcqderstuvwxyzJfgABCDEFGHI

54 """Name of the instance's class, used in __repr__.""" 

55 return self.__class__.__name__ 1abhijklmnopcqderstuvwxyzfgABCDEFGHI

56 

57 def __repr_recursion__(self, object: Any) -> str: 1abhijklmnopcqderstuvwxyzJfgABCDEFGHI

58 """Returns the string representation of a recursive object.""" 

59 # This is copied over from the stdlib `pprint` module: 

60 return f'<Recursion on {type(object).__name__} with id={id(object)}>' 1abhijklmnopcqderstuvwxyzfgABCDEFGHI

61 

62 def __repr_str__(self, join_str: str) -> str: 1abhijklmnopcqderstuvwxyzJfgABCDEFGHI

63 return join_str.join(repr(v) if a is None else f'{a}={v!r}' for a, v in self.__repr_args__()) 1abhijklmnopcqderstuvwxyzfgABCDEFGHI

64 

65 def __pretty__(self, fmt: typing.Callable[[Any], Any], **kwargs: Any) -> typing.Generator[Any, None, None]: 1abhijklmnopcqderstuvwxyzJfgABCDEFGHI

66 """Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.""" 

67 yield self.__repr_name__() + '(' 1abhijklmnopcqderstuvwxyzfgABCDEFGHI

68 yield 1 1abhijklmnopcqderstuvwxyzfgABCDEFGHI

69 for name, value in self.__repr_args__(): 1abhijklmnopcqderstuvwxyzfgABCDEFGHI

70 if name is not None: 1abhijklmnopcqderstuvwxyzfgABCDEFGHI

71 yield name + '=' 1abhijklmnopcqderstuvwxyzfgABCDEFGHI

72 yield fmt(value) 1abhijklmnopcqderstuvwxyzfgABCDEFGHI

73 yield ',' 1abhijklmnopcqderstuvwxyzfgABCDEFGHI

74 yield 0 1abhijklmnopcqderstuvwxyzfgABCDEFGHI

75 yield -1 1abhijklmnopcqderstuvwxyzfgABCDEFGHI

76 yield ')' 1abhijklmnopcqderstuvwxyzfgABCDEFGHI

77 

78 def __rich_repr__(self) -> RichReprResult: 1abhijklmnopcqderstuvwxyzJfgABCDEFGHI

79 """Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.""" 

80 for name, field_repr in self.__repr_args__(): 1abhijklmnopcqderstuvwxyzfgABCDEFGHI

81 if name is None: 1abhijklmnopcqderstuvwxyzfgABCDEFGHI

82 yield field_repr 1abhijklmnopcqderstuvwxyzfgABCDEFGHI

83 else: 

84 yield name, field_repr 1abhijklmnopcqderstuvwxyzfgABCDEFGHI

85 

86 def __str__(self) -> str: 1abhijklmnopcqderstuvwxyzJfgABCDEFGHI

87 return self.__repr_str__(' ') 1abhijklmnopcqderstuvwxyzfgABCDEFGHI

88 

89 def __repr__(self) -> str: 1abhijklmnopcqderstuvwxyzJfgABCDEFGHI

90 return f'{self.__repr_name__()}({self.__repr_str__(", ")})' 1abhijklmnopcqderstuvwxyzfgABCDEFGHI

91 

92 

93def display_as_type(obj: Any) -> str: 1abhijklmnopcqderstuvwxyzJfgABCDEFGHI

94 """Pretty representation of a type, should be as close as possible to the original type definition string. 

95 

96 Takes some logic from `typing._type_repr`. 

97 """ 

98 if isinstance(obj, (types.FunctionType, types.BuiltinFunctionType)): 1abhijklmnopcqderstuvwxyzJfgABCDEFGHI

99 return obj.__name__ 1abhijklmnopcqderstuvwxyzfgABCDEFGHI

100 elif obj is ...: 1abhijklmnopcqderstuvwxyzJfgABCDEFGHI

101 return '...' 1abhijklmnopcqderstuvwxyzfgABCDEFGHI

102 elif isinstance(obj, Representation): 1abhijklmnopcqderstuvwxyzJfgABCDEFGHI

103 return repr(obj) 1abhijklmnopcqderstuvwxyzfgABCDEFGHI

104 elif isinstance(obj, typing.ForwardRef) or typing_objects.is_typealiastype(obj): 1abhijklmnopcqderstuvwxyzJfgABCDEFGHI

105 return str(obj) 1abhijklmnopcqderstuvwxyzfgABCDEFGHI

106 

107 if not isinstance(obj, (_typing_extra.typing_base, _typing_extra.WithArgsTypes, type)): 1abhijklmnopcqderstuvwxyzJfgABCDEFGHI

108 obj = obj.__class__ 1abhijklmnopcqderstuvwxyzfgABCDEFGHI

109 

110 if is_union_origin(typing_extensions.get_origin(obj)): 1abhijklmnopcqderstuvwxyzJfgABCDEFGHI

111 args = ', '.join(map(display_as_type, typing_extensions.get_args(obj))) 1abhijklmnopcqderstuvwxyzfgABCDEFGHI

112 return f'Union[{args}]' 1abhijklmnopcqderstuvwxyzfgABCDEFGHI

113 elif isinstance(obj, _typing_extra.WithArgsTypes): 1abhijklmnopcqderstuvwxyzJfgABCDEFGHI

114 if typing_objects.is_literal(typing_extensions.get_origin(obj)): 1abhijklmnopcqderstuvwxyzfgABCDEFGHI

115 args = ', '.join(map(repr, typing_extensions.get_args(obj))) 1abhijklmnopcqderstuvwxyzfgABCDEFGHI

116 else: 

117 args = ', '.join(map(display_as_type, typing_extensions.get_args(obj))) 1abhijklmnopcqderstuvwxyzfgABCDEFGHI

118 try: 1abhijklmnopcqderstuvwxyzfgABCDEFGHI

119 return f'{obj.__qualname__}[{args}]' 1abhijklmnopcqderstuvwxyzfgABCDEFGHI

120 except AttributeError: 1abcdefg

121 return str(obj).replace('typing.', '').replace('typing_extensions.', '') # handles TypeAliasType in 3.12 1abcdefg

122 elif isinstance(obj, type): 1abhijklmnopcqderstuvwxyzJfgABCDEFGHI

123 return obj.__qualname__ 1abhijklmnopcqderstuvwxyzJfgABCDEFGHI

124 else: 

125 return repr(obj).replace('typing.', '').replace('typing_extensions.', '') 1abhijklmnopcqderstuvwxyzfgABCDEFGHI