|
| 1 | +""":mod:`dataclasses` utilities. |
| 2 | +
|
| 3 | +Note |
| 4 | +---- |
| 5 | +This is an internal API not covered by versioning policy. |
| 6 | +""" |
| 7 | +import dataclasses |
| 8 | +from operator import attrgetter |
| 9 | + |
| 10 | + |
| 11 | +class SkipDefaultFieldsReprMixin: |
| 12 | + r"""Skip default fields in :func:`~dataclasses.dataclass` |
| 13 | + :func:`object representation <repr()>`. |
| 14 | +
|
| 15 | + Notes |
| 16 | + ----- |
| 17 | +
|
| 18 | + Credit: Pietro Oldrati, 2022-05-08, Unilicense |
| 19 | +
|
| 20 | + https://stackoverflow.com/a/72161437/1396928 |
| 21 | +
|
| 22 | + Examples |
| 23 | + -------- |
| 24 | +
|
| 25 | + >>> @dataclasses.dataclass() |
| 26 | + ... class Item: |
| 27 | + ... name: str |
| 28 | + ... unit_price: float = 1.00 |
| 29 | + ... quantity_on_hand: int = 0 |
| 30 | + ... |
| 31 | +
|
| 32 | + >>> @dataclasses.dataclass(repr=False) |
| 33 | + ... class ItemWithMixin(SkipDefaultFieldsReprMixin): |
| 34 | + ... name: str |
| 35 | + ... unit_price: float = 1.00 |
| 36 | + ... quantity_on_hand: int = 0 |
| 37 | + ... |
| 38 | +
|
| 39 | + >>> Item('Test') |
| 40 | + Item(name='Test', unit_price=1.0, quantity_on_hand=0) |
| 41 | +
|
| 42 | + >>> ItemWithMixin('Test') |
| 43 | + ItemWithMixin(name=Test) |
| 44 | +
|
| 45 | + >>> Item('Test', quantity_on_hand=2) |
| 46 | + Item(name='Test', unit_price=1.0, quantity_on_hand=2) |
| 47 | +
|
| 48 | + >>> ItemWithMixin('Test', quantity_on_hand=2) |
| 49 | + ItemWithMixin(name=Test, quantity_on_hand=2) |
| 50 | +
|
| 51 | + If you want to copy/paste the :meth:`~.__repr__()` |
| 52 | + directly, you can omit the ``repr=False``: |
| 53 | +
|
| 54 | + >>> @dataclasses.dataclass |
| 55 | + ... class ItemWithMixin(SkipDefaultFieldsReprMixin): |
| 56 | + ... name: str |
| 57 | + ... unit_price: float = 1.00 |
| 58 | + ... quantity_on_hand: int = 0 |
| 59 | + ... __repr__ = SkipDefaultFieldsReprMixin.__repr__ |
| 60 | + ... |
| 61 | +
|
| 62 | + >>> ItemWithMixin('Test') |
| 63 | + ItemWithMixin(name=Test) |
| 64 | +
|
| 65 | + >>> ItemWithMixin('Test', unit_price=2.00) |
| 66 | + ItemWithMixin(name=Test, unit_price=2.0) |
| 67 | +
|
| 68 | + >>> item = ItemWithMixin('Test') |
| 69 | + >>> item.unit_price = 2.05 |
| 70 | +
|
| 71 | + >>> item |
| 72 | + ItemWithMixin(name=Test, unit_price=2.05) |
| 73 | + """ |
| 74 | + |
| 75 | + def __repr__(self) -> str: |
| 76 | + """Omit default fields in object representation.""" |
| 77 | + nodef_f_vals = ( |
| 78 | + (f.name, attrgetter(f.name)(self)) |
| 79 | + for f in dataclasses.fields(self) |
| 80 | + if attrgetter(f.name)(self) != f.default |
| 81 | + ) |
| 82 | + |
| 83 | + nodef_f_repr = ", ".join(f"{name}={value}" for name, value in nodef_f_vals) |
| 84 | + return f"{self.__class__.__name__}({nodef_f_repr})" |
0 commit comments