1from typing import Any, Iterable, List, Union, Tuple, Type, TypeVar 2 3 4T = TypeVar("T") 5 6 7RichReprResult = Iterable[Union[Any, Tuple[Any], Tuple[str, Any], Tuple[str, Any, Any]]] 8 9 10def rich_repr(cls: Type[T]) -> Type[T]: 11 """Class decorator to create __repr__ from __rich_repr__""" 12 13 def auto_repr(self) -> str: 14 repr_str: List[str] = [] 15 append = repr_str.append 16 for arg in self.__rich_repr__(): 17 if isinstance(arg, tuple): 18 if len(arg) == 1: 19 append(repr(arg[0])) 20 else: 21 key, value, *default = arg 22 if len(default) and default[0] == value: 23 continue 24 append(f"{key}={value!r}") 25 else: 26 append(repr(arg)) 27 return f"{self.__class__.__name__}({', '.join(repr_str)})" 28 29 auto_repr.__doc__ = "Return repr(self)" 30 cls.__repr__ = auto_repr # type: ignore 31 32 return cls 33