1"""Tools to provide pretty/human-readable display of objects."""
2
3from __future__ import annotations as _annotations
4
5import types
6import typing
7from typing import Any
8
9import typing_extensions
10from typing_inspection import typing_objects
11from typing_inspection.introspection import is_union_origin
12
13from . import _typing_extra
14
15if typing.TYPE_CHECKING:
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):
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:
28 return str(self)
29
30
31class Representation:
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]
39
40 def __repr_args__(self) -> ReprArgs:
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__
48 if not attrs_names and hasattr(self, '__dict__'):
49 attrs_names = self.__dict__.keys()
50 attrs = ((s, getattr(self, s)) for s in attrs_names)
51 return [(a, v if v is not self else self.__repr_recursion__(v)) for a, v in attrs if v is not None]
52
53 def __repr_name__(self) -> str:
54 """Name of the instance's class, used in __repr__."""
55 return self.__class__.__name__
56
57 def __repr_recursion__(self, object: Any) -> str:
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)}>'
61
62 def __repr_str__(self, join_str: str) -> str:
63 return join_str.join(repr(v) if a is None else f'{a}={v!r}' for a, v in self.__repr_args__())
64
65 def __pretty__(self, fmt: typing.Callable[[Any], Any], **kwargs: Any) -> typing.Generator[Any, None, None]:
66 """Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects."""
67 yield self.__repr_name__() + '('
68 yield 1
69 for name, value in self.__repr_args__():
70 if name is not None:
71 yield name + '='
72 yield fmt(value)
73 yield ','
74 yield 0
75 yield -1
76 yield ')'
77
78 def __rich_repr__(self) -> RichReprResult:
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__():
81 if name is None:
82 yield field_repr
83 else:
84 yield name, field_repr
85
86 def __str__(self) -> str:
87 return self.__repr_str__(' ')
88
89 def __repr__(self) -> str:
90 return f'{self.__repr_name__()}({self.__repr_str__(", ")})'
91
92
93def display_as_type(obj: Any) -> str:
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)):
99 return obj.__name__
100 elif obj is ...:
101 return '...'
102 elif isinstance(obj, Representation):
103 return repr(obj)
104 elif isinstance(obj, typing.ForwardRef) or typing_objects.is_typealiastype(obj):
105 return str(obj)
106
107 if not isinstance(obj, (_typing_extra.typing_base, _typing_extra.WithArgsTypes, type)):
108 obj = obj.__class__
109
110 if is_union_origin(typing_extensions.get_origin(obj)):
111 args = ', '.join(map(display_as_type, typing_extensions.get_args(obj)))
112 return f'Union[{args}]'
113 elif isinstance(obj, _typing_extra.WithArgsTypes):
114 if typing_objects.is_literal(typing_extensions.get_origin(obj)):
115 args = ', '.join(map(repr, typing_extensions.get_args(obj)))
116 else:
117 args = ', '.join(map(display_as_type, typing_extensions.get_args(obj)))
118 try:
119 return f'{obj.__qualname__}[{args}]'
120 except AttributeError:
121 return str(obj).replace('typing.', '').replace('typing_extensions.', '') # handles TypeAliasType in 3.12
122 elif isinstance(obj, type):
123 return obj.__qualname__
124 else:
125 return repr(obj).replace('typing.', '').replace('typing_extensions.', '')