_repr.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. """Tools to provide pretty/human-readable display of objects."""
  2. from __future__ import annotations as _annotations
  3. import types
  4. import typing
  5. from typing import Any
  6. import typing_extensions
  7. from . import _typing_extra
  8. if typing.TYPE_CHECKING:
  9. ReprArgs: typing_extensions.TypeAlias = 'typing.Iterable[tuple[str | None, Any]]'
  10. RichReprResult: typing_extensions.TypeAlias = (
  11. 'typing.Iterable[Any | tuple[Any] | tuple[str, Any] | tuple[str, Any, Any]]'
  12. )
  13. class PlainRepr(str):
  14. """String class where repr doesn't include quotes. Useful with Representation when you want to return a string
  15. representation of something that is valid (or pseudo-valid) python.
  16. """
  17. def __repr__(self) -> str:
  18. return str(self)
  19. class Representation:
  20. # Mixin to provide `__str__`, `__repr__`, and `__pretty__` and `__rich_repr__` methods.
  21. # `__pretty__` is used by [devtools](https://python-devtools.helpmanual.io/).
  22. # `__rich_repr__` is used by [rich](https://rich.readthedocs.io/en/stable/pretty.html).
  23. # (this is not a docstring to avoid adding a docstring to classes which inherit from Representation)
  24. # we don't want to use a type annotation here as it can break get_type_hints
  25. __slots__ = () # type: typing.Collection[str]
  26. def __repr_args__(self) -> ReprArgs:
  27. """Returns the attributes to show in __str__, __repr__, and __pretty__ this is generally overridden.
  28. Can either return:
  29. * name - value pairs, e.g.: `[('foo_name', 'foo'), ('bar_name', ['b', 'a', 'r'])]`
  30. * or, just values, e.g.: `[(None, 'foo'), (None, ['b', 'a', 'r'])]`
  31. """
  32. attrs_names = self.__slots__
  33. if not attrs_names and hasattr(self, '__dict__'):
  34. attrs_names = self.__dict__.keys()
  35. attrs = ((s, getattr(self, s)) for s in attrs_names)
  36. return [(a, v if v is not self else self.__repr_recursion__(v)) for a, v in attrs if v is not None]
  37. def __repr_name__(self) -> str:
  38. """Name of the instance's class, used in __repr__."""
  39. return self.__class__.__name__
  40. def __repr_recursion__(self, object: Any) -> str:
  41. """Returns the string representation of a recursive object."""
  42. # This is copied over from the stdlib `pprint` module:
  43. return f'<Recursion on {type(object).__name__} with id={id(object)}>'
  44. def __repr_str__(self, join_str: str) -> str:
  45. return join_str.join(repr(v) if a is None else f'{a}={v!r}' for a, v in self.__repr_args__())
  46. def __pretty__(self, fmt: typing.Callable[[Any], Any], **kwargs: Any) -> typing.Generator[Any, None, None]:
  47. """Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects."""
  48. yield self.__repr_name__() + '('
  49. yield 1
  50. for name, value in self.__repr_args__():
  51. if name is not None:
  52. yield name + '='
  53. yield fmt(value)
  54. yield ','
  55. yield 0
  56. yield -1
  57. yield ')'
  58. def __rich_repr__(self) -> RichReprResult:
  59. """Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects."""
  60. for name, field_repr in self.__repr_args__():
  61. if name is None:
  62. yield field_repr
  63. else:
  64. yield name, field_repr
  65. def __str__(self) -> str:
  66. return self.__repr_str__(' ')
  67. def __repr__(self) -> str:
  68. return f'{self.__repr_name__()}({self.__repr_str__(", ")})'
  69. def display_as_type(obj: Any) -> str:
  70. """Pretty representation of a type, should be as close as possible to the original type definition string.
  71. Takes some logic from `typing._type_repr`.
  72. """
  73. if isinstance(obj, (types.FunctionType, types.BuiltinFunctionType)):
  74. return obj.__name__
  75. elif obj is ...:
  76. return '...'
  77. elif isinstance(obj, Representation):
  78. return repr(obj)
  79. elif isinstance(obj, typing.ForwardRef) or _typing_extra.is_type_alias_type(obj):
  80. return str(obj)
  81. if not isinstance(obj, (_typing_extra.typing_base, _typing_extra.WithArgsTypes, type)):
  82. obj = obj.__class__
  83. if _typing_extra.origin_is_union(typing_extensions.get_origin(obj)):
  84. args = ', '.join(map(display_as_type, typing_extensions.get_args(obj)))
  85. return f'Union[{args}]'
  86. elif isinstance(obj, _typing_extra.WithArgsTypes):
  87. if _typing_extra.is_literal(obj):
  88. args = ', '.join(map(repr, typing_extensions.get_args(obj)))
  89. else:
  90. args = ', '.join(map(display_as_type, typing_extensions.get_args(obj)))
  91. try:
  92. return f'{obj.__qualname__}[{args}]'
  93. except AttributeError:
  94. return str(obj).replace('typing.', '').replace('typing_extensions.', '') # handles TypeAliasType in 3.12
  95. elif isinstance(obj, type):
  96. return obj.__qualname__
  97. else:
  98. return repr(obj).replace('typing.', '').replace('typing_extensions.', '')