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