Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/rich/repr.py: 40%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

81 statements  

1from functools import partial 

2from typing import Any, Callable, Iterable, TypeVar, overload 

3 

4T = TypeVar("T") 

5 

6 

7Result = Iterable[Any | tuple[Any] | tuple[str, Any] | tuple[str, Any, Any]] 

8RichReprResult = Result 

9 

10 

11class ReprError(Exception): 

12 """An error occurred when attempting to build a repr.""" 

13 

14 

15@overload 

16def auto(cls: type[T] | None) -> type[T]: ... 

17 

18 

19@overload 

20def auto(*, angular: bool = False) -> Callable[[type[T]], type[T]]: ... 

21 

22 

23def auto( 

24 cls: type[T] | None = None, *, angular: bool | None = None 

25) -> type[T] | Callable[[type[T]], type[T]]: 

26 """Class decorator to create __repr__ from __rich_repr__""" 

27 

28 def do_replace(cls: type[T], angular: bool | None = None) -> type[T]: 

29 def auto_repr(self: T) -> str: 

30 """Create repr string from __rich_repr__""" 

31 repr_str: list[str] = [] 

32 append = repr_str.append 

33 

34 angular: bool = getattr(self.__rich_repr__, "angular", False) # type: ignore[attr-defined] 

35 for arg in self.__rich_repr__(): # type: ignore[attr-defined] 

36 if isinstance(arg, tuple): 

37 if len(arg) == 1: 

38 append(repr(arg[0])) 

39 else: 

40 key, value, *default = arg 

41 if key is None: 

42 append(repr(value)) 

43 else: 

44 if default and default[0] == value: 

45 continue 

46 append(f"{key}={value!r}") 

47 else: 

48 append(repr(arg)) 

49 if angular: 

50 return f"<{self.__class__.__name__} {' '.join(repr_str)}>" 

51 else: 

52 return f"{self.__class__.__name__}({', '.join(repr_str)})" 

53 

54 def auto_rich_repr(self: type[T]) -> Result: 

55 """Auto generate __rich_rep__ from signature of __init__""" 

56 try: 

57 import inspect 

58 

59 signature = inspect.signature(self.__init__) 

60 for name, param in signature.parameters.items(): 

61 if param.kind == param.POSITIONAL_ONLY: 

62 yield getattr(self, name) 

63 elif param.kind in ( 

64 param.POSITIONAL_OR_KEYWORD, 

65 param.KEYWORD_ONLY, 

66 ): 

67 if param.default is param.empty: 

68 yield getattr(self, param.name) 

69 else: 

70 yield param.name, getattr(self, param.name), param.default 

71 except Exception as error: 

72 raise ReprError( 

73 f"Failed to auto generate __rich_repr__; {error}" 

74 ) from None 

75 

76 if not hasattr(cls, "__rich_repr__"): 

77 auto_rich_repr.__doc__ = "Build a rich repr" 

78 cls.__rich_repr__ = auto_rich_repr # type: ignore[attr-defined] 

79 

80 auto_repr.__doc__ = "Return repr(self)" 

81 cls.__repr__ = auto_repr # type: ignore[assignment] 

82 if angular is not None: 

83 cls.__rich_repr__.angular = angular # type: ignore[attr-defined] 

84 return cls 

85 

86 if cls is None: 

87 return partial(do_replace, angular=angular) 

88 else: 

89 return do_replace(cls, angular=angular) 

90 

91 

92@overload 

93def rich_repr(cls: type[T] | None) -> type[T]: ... 

94 

95 

96@overload 

97def rich_repr(*, angular: bool = False) -> Callable[[type[T]], type[T]]: ... 

98 

99 

100def rich_repr( 

101 cls: type[T] | None = None, *, angular: bool = False 

102) -> type[T] | Callable[[type[T]], type[T]]: 

103 if cls is None: 

104 return auto(angular=angular) 

105 else: 

106 return auto(cls) 

107 

108 

109if __name__ == "__main__": 

110 

111 @auto 

112 class Foo: 

113 def __rich_repr__(self) -> Result: 

114 yield "foo" 

115 yield "bar", {"shopping": ["eggs", "ham", "pineapple"]} 

116 yield "buy", "hand sanitizer" 

117 

118 foo = Foo() 

119 from rich.console import Console 

120 

121 console = Console() 

122 

123 console.rule("Standard repr") 

124 console.print(foo) 

125 

126 console.print(foo, width=60) 

127 console.print(foo, width=30) 

128 

129 console.rule("Angular repr") 

130 Foo.__rich_repr__.angular = True # type: ignore[attr-defined] 

131 

132 console.print(foo) 

133 

134 console.print(foo, width=60) 

135 console.print(foo, width=30)