Skip to content

Commit

Permalink
mypy: comply with strict mode and resolve all 'type: ignore' cases
Browse files Browse the repository at this point in the history
Tested with mypy 1.5.1 on Python 3.11.

This changes `ByteString` into `Union[bytes, bytearray, memoryview]`.
See python/cpython#91896.

Python 3.11 documentation on `typing.ByteString`:

> Deprecated since version 3.9, will be removed in version 3.14: Prefer
> typing_extensions.Buffer, or a union like
> `bytes | bytearray | memoryview`.

Python 3.8 documentation on `typing.ByteString` [2]:

> This type represents the types `bytes`, `bytearray`, and `memoryview`
> of byte sequences.
>
> As a shorthand for this type, `bytes` can be used to annotate
> arguments of any of the types mentioned above.

While at it, also add the return types for special methods which are
still optional in mypy strict mode (Ruff's ANN024 rule [3]).

[1]: https://docs.python.org/3.11/library/typing.html#typing.ByteString
[2]: https://docs.python.org/3.8/library/typing.html#typing.ByteString
[3]: https://docs.astral.sh/ruff/rules/missing-return-type-special-method/
  • Loading branch information
gertvdijk committed Sep 30, 2023
1 parent 5ee0ee1 commit 64727b7
Showing 1 changed file with 40 additions and 17 deletions.
57 changes: 40 additions & 17 deletions crc.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
from dataclasses import dataclass
from typing import (
BinaryIO,
ByteString,
Iterable,
Iterator,
List,
Expand All @@ -27,7 +26,7 @@ class Byte(numbers.Number):
BIT_LENGTH: int = 8
BIT_MASK: int = 0xFF

def __init__(self, value: int = 0x00):
def __init__(self, value: int = 0x00) -> None:
self._value = value & Byte.BIT_MASK

def __add__(self, other: "Byte") -> "Byte":
Expand Down Expand Up @@ -62,15 +61,15 @@ def __getitem__(self, index: int) -> int:
def __iter__(self) -> Iterator[int]:
return (self[i] for i in range(0, len(self)))

def __int__(self):
def __int__(self) -> int:
return self.value

@property
def value(self) -> int:
return self._value & Byte.BIT_MASK

@value.setter
def value(self, value) -> None:
def value(self, value: int) -> None:
self._value = value & Byte.BIT_MASK

def reversed(self) -> "Byte":
Expand All @@ -91,7 +90,7 @@ class AbstractRegister(metaclass=abc.ABCMeta):
"""

@abc.abstractmethod
def init(self):
def init(self) -> None:
"""
Initializes the crc register.
"""
Expand Down Expand Up @@ -164,7 +163,7 @@ class BasicRegister(AbstractRegister):
an overwrite for the _process_byte method.
"""

def __init__(self, configuration: Configuration):
def __init__(self, configuration: Configuration) -> None:
"""
Create a new BasicRegister.
Expand All @@ -174,7 +173,7 @@ def __init__(self, configuration: Configuration):
if isinstance(configuration, enum.Enum):
configuration = configuration.value
self._topbit = 1 << (configuration.width - 1)
self._bitmask = 2**configuration.width - 1
self._bitmask = int(2**configuration.width - 1)
self._config = configuration
self._register = configuration.init_value & self._bitmask

Expand Down Expand Up @@ -259,7 +258,7 @@ def register(self) -> int:
return self._register & self._bitmask

@register.setter
def register(self, value) -> None:
def register(self, value: int) -> None:
self._register = value & self._bitmask


Expand Down Expand Up @@ -294,7 +293,7 @@ class TableBasedRegister(BasicRegister):
register like `Register`.
"""

def __init__(self, configuration: Configuration):
def __init__(self, configuration: Configuration) -> None:
"""
Creates a new table based crc register.
Expand Down Expand Up @@ -345,7 +344,7 @@ def create_lookup_table(width: int, polynomial: int) -> List[int]:


class Calculator:
def __init__(self, configuration: Configuration, optimized: bool = False):
def __init__(self, configuration: Configuration, optimized: bool = False) -> None:
"""
Creates a new Calculator.
Expand All @@ -364,7 +363,15 @@ def __init__(self, configuration: Configuration, optimized: bool = False):
self._crc_register = klass(configuration)

def checksum(
self, data: Union[int, ByteString, BinaryIO, Iterable[ByteString]]
self,
data: Union[
int,
bytes,
bytearray,
memoryview,
BinaryIO,
Iterable[Union[bytes, bytearray, memoryview]],
],
) -> int:
"""
Calculates the checksum for the given data.
Expand All @@ -382,7 +389,14 @@ def checksum(

def verify(
self,
data: Union[int, ByteString, BinaryIO, Iterable[ByteString]],
data: Union[
int,
bytes,
bytearray,
memoryview,
BinaryIO,
Iterable[Union[bytes, bytearray, memoryview]],
],
expected: int,
) -> bool:
"""
Expand All @@ -400,13 +414,22 @@ def verify(


def _bytes_generator(
data: Union[int, ByteString, BinaryIO, Iterable[ByteString]] # type: ignore
data: Union[
int,
bytes,
bytearray,
memoryview,
BinaryIO,
Iterable[Union[bytes, bytearray, memoryview]],
]
) -> Iterable[bytes]:
if isinstance(data, int):
yield data.to_bytes(1, "big")
elif isinstance(data, ByteString): # type: ignore
yield bytes(data) # type: ignore
elif isinstance(data, (Iterable, BinaryIO)): # type: ignore
elif isinstance(data, bytes):
yield data
elif isinstance(data, (bytearray, memoryview)):
yield bytes(data)
elif isinstance(data, (Iterable, BinaryIO)):
yield from (bytes(e) for e in data)
else:
raise TypeError(f"Unsupported parameter type: {type(data)}")
Expand Down Expand Up @@ -598,7 +621,7 @@ def table(args: argparse.Namespace) -> bool:
return True


def main(argv: Optional[List[str]] = None):
def main(argv: Optional[List[str]] = None) -> None:
parser = _argument_parser()
args = parser.parse_args(argv)
if "func" in args:
Expand Down

0 comments on commit 64727b7

Please sign in to comment.