From f335840d973d57926f9e23d96b5a1139f790909a Mon Sep 17 00:00:00 2001 From: Scott Griffiths Date: Wed, 5 Feb 2025 18:53:05 +0000 Subject: [PATCH] Moving DtypeName to the Dtype base class and giving DtypeTuple's all the name 'tuple'. --- bitformat/_common.py | 1 + bitformat/_dtypes.py | 25 ++++++++----------------- 2 files changed, 9 insertions(+), 17 deletions(-) diff --git a/bitformat/_common.py b/bitformat/_common.py index cfdac65..b7d416c 100644 --- a/bitformat/_common.py +++ b/bitformat/_common.py @@ -32,6 +32,7 @@ class DtypeName(Enum): BITS = 'bits' # Bits object BOOL = 'bool' # boolean PAD = 'pad' # padding + TUPLE = 'tuple' # tuple of dtypes def __str__(self): return self.value diff --git a/bitformat/_dtypes.py b/bitformat/_dtypes.py index 389aec8..872d3fc 100644 --- a/bitformat/_dtypes.py +++ b/bitformat/_dtypes.py @@ -53,6 +53,7 @@ class Dtype(abc.ABC): """ + _name: DtypeName _endianness: Endianness def __new__(cls, token: str | None = None, /) -> Dtype: @@ -106,6 +107,11 @@ def unpack(self, b: BitsType, /): """ ... + @property + def name(self) -> DtypeName: + """An Enum giving the name of the data type.""" + return self._name + @property def endianness(self) -> Endianness: """The endianness of the data type.""" @@ -191,14 +197,8 @@ def __len__(self): class DtypeSingle(Dtype): - _name: DtypeName _size: int - @property - def name(self) -> DtypeName: - """An Enum giving the name of the data type.""" - return self._name - @classmethod @functools.lru_cache(CACHE_SIZE) def _create(cls, definition: DtypeDefinition, size: int, @@ -336,15 +336,9 @@ def bit_length(self) -> int: class DtypeArray(Dtype): - _name: DtypeName _size: int _items: int | None - @property - def name(self) -> DtypeName: - """An Enum giving the name of the data type.""" - return self._name - @classmethod @functools.lru_cache(CACHE_SIZE) def _create(cls, definition: DtypeDefinition, size: int, items: int = 1, @@ -632,6 +626,7 @@ def __new__(cls, s: str) -> DtypeTuple: def from_params(cls, dtypes: Sequence[Dtype | str]) -> DtypeTuple: x = super().__new__(cls) x._dtypes = [] + x._name = DtypeName.TUPLE for d in dtypes: dtype = d if isinstance(d, Dtype) else Dtype.from_string(d) if dtype.bit_length == 0: @@ -654,11 +649,7 @@ def pack(self, values: Sequence[Any]) -> bitformat.Bits: raise ValueError(f"Expected {len(self)} values, but got {len(values)}.") return bitformat.Bits.from_joined(dtype.pack(value) for dtype, value in zip(self._dtypes, values)) - def unpack( - self, - b: bitformat.Bits | str | Iterable[Any] | bytearray | bytes | memoryview, - /, - ) -> tuple[tuple[Any] | Any]: + def unpack(self, b: bitformat.Bits | str | Iterable[Any] | bytearray | bytes | memoryview, /) -> tuple[tuple[Any] | Any]: """Unpack a Bits to find its value. The b parameter should be a Bits of the appropriate length, or an object that can be converted to a Bits.