|
| 1 | +""" |
| 2 | +assertionlib.dataclass |
| 3 | +====================== |
| 4 | +
|
| 5 | +A dataclass with a number of generic pre-defined (magic) methods. |
| 6 | +
|
| 7 | +Index |
| 8 | +----- |
| 9 | +.. currentmodule:: assertionlib.dataclass |
| 10 | +.. autosummary:: |
| 11 | + AbstractDataClass |
| 12 | +
|
| 13 | +API |
| 14 | +--- |
| 15 | +.. autoclass:: AbstractDataClass |
| 16 | + :members: |
| 17 | + :private-members: |
| 18 | + :special-members: |
| 19 | +
|
| 20 | +""" |
| 21 | + |
| 22 | +import textwrap |
| 23 | +from copy import deepcopy |
| 24 | +from typing import (Any, Dict, FrozenSet, Iterable, Tuple) |
| 25 | + |
| 26 | + |
| 27 | +class AbstractDataClass: |
| 28 | + """A dataclass with a number of generic pre-defined (magic) methods.""" |
| 29 | + |
| 30 | + #: A :class:`frozenset` with the names of private instance variables. |
| 31 | + #: These attributes will be excluded whenever calling :meth:`AbstractDataClass.as_dict`, |
| 32 | + #: printing or comparing objects. |
| 33 | + _PRIVATE_ATTR: FrozenSet[str] = frozenset() |
| 34 | + |
| 35 | + def __str__(self) -> str: |
| 36 | + """Return a string representation of this instance.""" |
| 37 | + def _str(k: str, v: Any) -> str: |
| 38 | + return f'{k:{width}} = ' + textwrap.indent(repr(v), indent2)[len(indent2):] |
| 39 | + |
| 40 | + width = max(len(k) for k in vars(self)) |
| 41 | + indent1 = ' ' * 4 |
| 42 | + indent2 = ' ' * (3 + width) |
| 43 | + iterable = self._str_iterator() |
| 44 | + ret = ',\n'.join(_str(k, v) for k, v in iterable) |
| 45 | + |
| 46 | + return f'{self.__class__.__name__}(\n{textwrap.indent(ret, indent1)}\n)' |
| 47 | + |
| 48 | + __repr__ = __str__ |
| 49 | + |
| 50 | + def _str_iterator(self) -> Iterable[Tuple[str, Any]]: |
| 51 | + """Return an iterable for the :meth:`AbstractDataClass.__str__` method.""" |
| 52 | + return ((k, v) for k, v in vars(self).items() if k not in self._PRIVATE_ATTR) |
| 53 | + |
| 54 | + def __eq__(self, value: Any) -> bool: |
| 55 | + """Check if this instance is equivalent to **value**.""" |
| 56 | + if type(self) is not type(value): |
| 57 | + return False |
| 58 | + |
| 59 | + try: |
| 60 | + for k, v1 in vars(self).items(): |
| 61 | + if k in self._PRIVATE_ATTR: |
| 62 | + continue |
| 63 | + v2 = getattr(value, k) |
| 64 | + assert v1 == v2 |
| 65 | + except (AttributeError, AssertionError): |
| 66 | + return False |
| 67 | + else: |
| 68 | + return True |
| 69 | + |
| 70 | + def copy(self, deep: bool = False) -> 'AbstractDataClass': |
| 71 | + """Return a deep or shallow copy of this instance. |
| 72 | +
|
| 73 | + Parameters |
| 74 | + ---------- |
| 75 | + deep : :class:`bool` |
| 76 | + Whether or not to return a deep or shallow copy. |
| 77 | +
|
| 78 | + Returns |
| 79 | + ------- |
| 80 | + :class:`AbstractDataClass` |
| 81 | + A new instance constructed from this instance. |
| 82 | +
|
| 83 | + """ |
| 84 | + cls = type(self) |
| 85 | + ret = cls.__new__(cls) |
| 86 | + ret.__dict__ = vars(self).copy() if not deep else deepcopy(vars(self)) |
| 87 | + return ret |
| 88 | + |
| 89 | + def __copy__(self) -> 'AbstractDataClass': |
| 90 | + """Return a shallow copy of this instance.""" |
| 91 | + return self.copy(deep=False) |
| 92 | + |
| 93 | + def __deepcopy__(self, memo=None) -> 'AbstractDataClass': |
| 94 | + """Return a deep copy of this instance.""" |
| 95 | + return self.copy(deep=True) |
| 96 | + |
| 97 | + def as_dict(self, return_private: bool = False) -> Dict[str, Any]: |
| 98 | + """Construct a dictionary from this instance with all non-private instance variables. |
| 99 | +
|
| 100 | + No attributes specified in :data:`AbstractDataClass._PRIVATE_ATTR` will be included in |
| 101 | + the to-be returned dictionary. |
| 102 | +
|
| 103 | + Parameters |
| 104 | + ---------- |
| 105 | + return_private : :class:`bool` |
| 106 | + If ``True``, return both public and private instance variables. |
| 107 | + Private instance variables are defined in :data:`AbstractDataClass._PRIVATE_ATTR`. |
| 108 | +
|
| 109 | + Returns |
| 110 | + ------- |
| 111 | + :class:`dict` [:class:`str`, :class:`object`] |
| 112 | + A dictionary of arrays with keyword arguments for initializing a new |
| 113 | + instance of this class. |
| 114 | +
|
| 115 | + See also |
| 116 | + -------- |
| 117 | + :meth:`AbstractDataClass.from_dict`: |
| 118 | + Construct a instance of this objects' class from a dictionary with keyword arguments. |
| 119 | +
|
| 120 | + """ |
| 121 | + ret = deepcopy(vars(self)) |
| 122 | + if not return_private: |
| 123 | + for key in self._PRIVATE_ATTR: |
| 124 | + del ret[key] |
| 125 | + return ret |
| 126 | + |
| 127 | + @classmethod |
| 128 | + def from_dict(cls, dct: Dict[str, Any]) -> 'AbstractDataClass': |
| 129 | + """Construct a instance of this objects' class from a dictionary with keyword arguments. |
| 130 | +
|
| 131 | + Parameters |
| 132 | + ---------- |
| 133 | + dct : :class:`dict` [:class:`str`, :class:`.Any`] |
| 134 | + A dictionary with keyword arguments for constructing a new |
| 135 | + :class:`AbstractDataClass` instance. |
| 136 | +
|
| 137 | + Returns |
| 138 | + ------- |
| 139 | + :class:`AbstractDataClass` |
| 140 | + A new instance of this object's class constructed from **dct**. |
| 141 | +
|
| 142 | + See also |
| 143 | + -------- |
| 144 | + :meth:`AbstractDataClass.as_dict`: |
| 145 | + Construct a dictionary from this instance with all non-private instance variables. |
| 146 | +
|
| 147 | + """ |
| 148 | + return cls(**dct) |
| 149 | + |
| 150 | + @classmethod |
| 151 | + def inherit_annotations(cls) -> type: |
| 152 | + """A decorator for inheriting annotations and docstrings. |
| 153 | +
|
| 154 | + Can be applied to methods of :class:`AbstractDataClass` subclasses to automatically |
| 155 | + inherit the docstring and annotations of identical-named functions of its superclass. |
| 156 | +
|
| 157 | + Examples |
| 158 | + -------- |
| 159 | + .. code:: python |
| 160 | +
|
| 161 | + >>> class sub_class(AbstractDataClass) |
| 162 | + ... |
| 163 | + ... @AbstractDataClass.inherit_annotations() |
| 164 | + ... def as_dict(self, return_private=False): |
| 165 | + ... pass |
| 166 | +
|
| 167 | + >>> sub_class.as_dict.__doc__ == AbstractDataClass.as_dict.__doc__ |
| 168 | + True |
| 169 | +
|
| 170 | + >>> sub_class.as_dict.__annotations__ == AbstractDataClass.as_dict.__annotations__ |
| 171 | + True |
| 172 | +
|
| 173 | + """ |
| 174 | + def decorator(sub_attr: type) -> type: |
| 175 | + super_attr = getattr(cls, sub_attr.__name__) |
| 176 | + sub_cls_name = sub_attr.__qualname__.split('.')[0] |
| 177 | + |
| 178 | + # Update annotations |
| 179 | + if not sub_attr.__annotations__: |
| 180 | + sub_attr.__annotations__ = dct = super_attr.__annotations__.copy() |
| 181 | + if 'return' in dct and dct['return'] == cls.__name__: |
| 182 | + dct['return'] = sub_attr.__qualname__.split('.')[0] |
| 183 | + |
| 184 | + # Update docstring |
| 185 | + if sub_attr.__doc__ is None: |
| 186 | + sub_attr.__doc__ = super_attr.__doc__.replace(cls.__name__, sub_cls_name) |
| 187 | + |
| 188 | + return sub_attr |
| 189 | + return decorator |
0 commit comments