|
1 | 1 | """A collection of implementation tools to can be used accross all modules.""" |
2 | 2 |
|
3 | | -from typing import TYPE_CHECKING, Any, Callable, Type, TypeVar |
| 3 | +from typing import TYPE_CHECKING, Any, Type, TypeVar |
4 | 4 |
|
5 | 5 | import attrs |
6 | 6 |
|
|
14 | 14 | _DecoratedClass = TypeVar("_DecoratedClass") |
15 | 15 |
|
16 | 16 |
|
17 | | -def implement_pretty_repr() -> Callable[ |
18 | | - [Type[_DecoratedClass]], Type[_DecoratedClass] |
19 | | -]: |
| 17 | +def implement_pretty_repr( |
| 18 | + decorated_class: Type[_DecoratedClass], |
| 19 | +) -> Type[_DecoratedClass]: |
20 | 20 | """Implement a pretty :code:`repr` in a class decorated by `attrs`.""" |
21 | | - |
22 | | - def decorator( |
23 | | - decorated_class: Type[_DecoratedClass], |
24 | | - ) -> Type[_DecoratedClass]: |
25 | | - if not attrs.has(decorated_class): |
26 | | - raise TypeError( |
27 | | - "Can only implement a pretty repr for a class created with" |
28 | | - " attrs" |
29 | | - ) |
30 | | - |
31 | | - def repr_pretty(self: Any, p: "PrettyPrinter", cycle: bool) -> None: |
32 | | - class_name = type(self).__name__ |
33 | | - if cycle: |
34 | | - p.text(f"{class_name}(...)") |
35 | | - else: |
36 | | - with p.group(indent=2, open=f"{class_name}("): |
37 | | - for field in attrs.fields(type(self)): |
38 | | - if not field.init: |
39 | | - continue |
40 | | - value = getattr(self, field.name) |
41 | | - p.breakable() |
42 | | - p.text(f"{field.name}=") |
43 | | - p.pretty(value) |
44 | | - p.text(",") |
45 | | - p.breakable() |
46 | | - p.text(")") |
47 | | - |
48 | | - # pylint: disable=protected-access |
49 | | - decorated_class._repr_pretty_ = repr_pretty # type: ignore[attr-defined] |
50 | | - return decorated_class |
51 | | - |
52 | | - return decorator |
| 21 | + if not attrs.has(decorated_class): |
| 22 | + raise TypeError( |
| 23 | + "Can only implement a pretty repr for a class created with attrs" |
| 24 | + ) |
| 25 | + |
| 26 | + def repr_pretty(self: Any, p: "PrettyPrinter", cycle: bool) -> None: |
| 27 | + class_name = type(self).__name__ |
| 28 | + if cycle: |
| 29 | + p.text(f"{class_name}(...)") |
| 30 | + else: |
| 31 | + with p.group(indent=2, open=f"{class_name}("): |
| 32 | + for field in attrs.fields(type(self)): |
| 33 | + if not field.init: |
| 34 | + continue |
| 35 | + value = getattr(self, field.name) |
| 36 | + p.breakable() |
| 37 | + p.text(f"{field.name}=") |
| 38 | + p.pretty(value) |
| 39 | + p.text(",") |
| 40 | + p.breakable() |
| 41 | + p.text(")") |
| 42 | + |
| 43 | + # pylint: disable=protected-access |
| 44 | + decorated_class._repr_pretty_ = repr_pretty # type: ignore[attr-defined] |
| 45 | + return decorated_class |
0 commit comments