From 6c2785a6024efebb8316f27e8c935c1095b980db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=87a=C4=9F=C4=B1l=20Ulu=C5=9Fahin?= Date: Tue, 1 Dec 2026 16:31:07 +0000 Subject: [PATCH 1/3] Add type annotation to sync backend --- src/hip/backends/sync.py | 46 +++++++++++++++++++++++----------------- 1 file changed, 27 insertions(+), 19 deletions(-) diff --git a/src/hip/backends/sync.py b/src/hip/backends/sync.py index 02106b5..f58e6ee 100644 --- a/src/hip/backends/sync.py +++ b/src/hip/backends/sync.py @@ -55,7 +55,7 @@ def close(self) -> None: pass self._socket.close() - def __repr__(self): + def __repr__(self) -> str: description = "" description += " TLS" if self._is_tls else "" description += " CLOSED" if self._is_closed else "" @@ -69,7 +69,7 @@ def __exit__( exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, traceback: types.TracebackType | None = None, - ): + ) -> None: self.close() @@ -80,11 +80,11 @@ def __init__(self, sock: socket.socket, address: tuple[str, int]) -> None: self._is_closed = False @property - def host(self): + def host(self) -> str: return self._address[0] @property - def port(self): + def port(self) -> int: return self._address[1] def accept(self) -> NetworkStream | None: @@ -99,7 +99,7 @@ def accept(self) -> NetworkStream | None: return NetworkStream(sock, address) return None - def close(self): + def close(self) -> None: self._is_closed = True self._server_socket.close() @@ -111,7 +111,7 @@ def __exit__( exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, traceback: types.TracebackType | None = None, - ): + ) -> None: self.close() @@ -122,36 +122,44 @@ def __init__( self.listener = listener self.handler = handler self._max_workers = 10 - self._executor = None - self._thread = None + self._executor: concurrent.futures.ThreadPoolExecutor | None = None self._streams: list[NetworkStream] = [] @property - def host(self): + def host(self) -> str: return self.listener.host @property - def port(self): + def port(self) -> int: return self.listener.port - def __enter__(self): + def __enter__(self) -> typing.Self: self._executor = concurrent.futures.ThreadPoolExecutor( max_workers=self._max_workers ) self._executor.submit(self._serve) return self - def __exit__(self, exc_type, exc_val, exc_tb): + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: types.TracebackType | None = None, + ) -> None: + executor = self._executor + assert executor is not None for stream in self._streams: stream.close() self.listener.close() - self._executor.shutdown(wait=True) + executor.shutdown(wait=True) - def _serve(self): + def _serve(self) -> None: + executor = self._executor + assert executor is not None while stream := self.listener.accept(): - self._executor.submit(self._handler, stream) + executor.submit(self._handler, stream) - def _handler(self, stream): + def _handler(self, stream: NetworkStream) -> None: try: self._streams.append(stream) self.handler(stream) @@ -161,7 +169,7 @@ def _handler(self, stream): class NetworkBackend: - def __init__(self, ssl_ctx: ssl.SSLContext | None = None): + def __init__(self, ssl_ctx: ssl.SSLContext | None = None) -> None: self._ssl_ctx = self.create_default_context() if ssl_ctx is None else ssl_ctx def create_default_context(self) -> ssl.SSLContext: @@ -205,7 +213,7 @@ def serve( listener = self.listen(host, port) return NetworkServer(listener, handler) - def __repr__(self): + def __repr__(self) -> str: return "" @@ -250,7 +258,7 @@ def get_current_timeout() -> float | None: return remaining -def sleep(dur: float): +def sleep(dur: float) -> None: """ A `sleep()` implementation that is aware of the current timeout context. """ From f4d169098d085dc588ac0a7835277f224f2fcd7a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=87a=C4=9F=C4=B1l=20Ulu=C5=9Fahin?= Date: Tue, 1 Dec 2026 16:45:01 +0000 Subject: [PATCH 2/3] Add type annotations to core --- src/hip/core/content.py | 8 ++++---- src/hip/core/request.py | 10 +++++----- src/hip/core/response.py | 10 +++++----- src/hip/core/streams.py | 20 ++++++++++++-------- src/hip/core/urlencode.py | 16 ++++++++-------- src/hip/core/urlparse.py | 2 +- 6 files changed, 35 insertions(+), 31 deletions(-) diff --git a/src/hip/core/content.py b/src/hip/core/content.py index fab4342..652c681 100644 --- a/src/hip/core/content.py +++ b/src/hip/core/content.py @@ -27,7 +27,7 @@ def headers(self) -> Headers: def parse(self, stream: Stream) -> "Content": raise NotImplementedError() - def __bytes__(self): + def __bytes__(self) -> bytes: raise TypeError( f"Content {self.__class__.__name__} does not support a bytes interface." ) @@ -70,7 +70,7 @@ def value(self) -> typing.Any: # dict and list style accessors, eg. for casting. def keys(self) -> typing.KeysView[str]: - return self._data.keys() + return typing.cast(typing.KeysView[str], self._data.keys()) def __len__(self) -> int: return len(self._data) @@ -81,8 +81,8 @@ def __getitem__(self, key: typing.Any) -> typing.Any: # Built-ins. def __eq__(self, other: object) -> bool: if isinstance(other, JSON): - return self._data == other._data - return self._data == other + return bool(self._data == other._data) + return bool(self._data == other) def __str__(self) -> str: return self._content.decode("utf-8") diff --git a/src/hip/core/request.py b/src/hip/core/request.py index 476be4a..bbc3197 100644 --- a/src/hip/core/request.py +++ b/src/hip/core/request.py @@ -18,7 +18,7 @@ class Method: - def __init__(self, method: str, standard=True): + def __init__(self, method: str, standard: bool = True) -> None: if standard: method = method.upper() if method not in STANDARD_METHODS: @@ -28,7 +28,7 @@ def __init__(self, method: str, standard=True): def has_body(self) -> bool: return self._method in ("POST", "PUT", "PATCH") - def __eq__(self, other) -> bool: + def __eq__(self, other: object) -> bool: return str(self) == str(other) def __bytes__(self) -> bytes: @@ -37,7 +37,7 @@ def __bytes__(self) -> bytes: def __str__(self) -> str: return self._method - def __repr__(self): + def __repr__(self) -> str: return f"" @@ -48,7 +48,7 @@ def __init__( url: URL | str, headers: Headers | dict[str, str] | None = None, content: Content | bytes | None = None, - ): + ) -> None: self.method = Method(method) if not isinstance(method, Method) else method self.url = URL(url) if not isinstance(url, URL) else url self.headers = Headers(headers) if not isinstance(headers, Headers) else headers @@ -79,5 +79,5 @@ def __init__( def body(self) -> bytes: return bytes(self.content) - def __repr__(self): + def __repr__(self) -> str: return f"" diff --git a/src/hip/core/response.py b/src/hip/core/response.py index 55f366a..4aa39d0 100644 --- a/src/hip/core/response.py +++ b/src/hip/core/response.py @@ -75,7 +75,7 @@ class StatusCode: 511: "Network Authentication Required", } - def __init__(self, status_code: int): + def __init__(self, status_code: int) -> None: if status_code < 100 or status_code > 999: raise ValueError(f"Invalid status code {status_code!r}") self.value = status_code @@ -119,8 +119,8 @@ def has_body(self) -> bool: def as_tuple(self) -> tuple[int, bytes]: return (self.value, self.reason_phrase.encode("ascii")) - def __eq__(self, other) -> bool: - return int(self) == int(other) + def __eq__(self, other: object) -> bool: + return bool(int(self) == int(other)) # type: ignore[call-overload] def __int__(self) -> int: return self.value @@ -139,7 +139,7 @@ def __init__( *, headers: Headers | dict[str, str] | None = None, content: Content | bytes | None = None, - ): + ) -> None: self.status_code = ( StatusCode(status_code) if not isinstance(status_code, StatusCode) @@ -169,5 +169,5 @@ def __init__( def body(self) -> bytes: return bytes(self.content) - def __repr__(self): + def __repr__(self) -> str: return f"" diff --git a/src/hip/core/streams.py b/src/hip/core/streams.py index caf4b18..44fd27b 100644 --- a/src/hip/core/streams.py +++ b/src/hip/core/streams.py @@ -1,6 +1,7 @@ import io import os import types +import typing __all__ = ["Stream"] @@ -15,7 +16,7 @@ def write(self, data: bytes) -> None: def close(self) -> None: raise NotImplementedError() - def __enter__(self): + def __enter__(self) -> typing.Self: return self def __exit__( @@ -23,12 +24,12 @@ def __exit__( exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, traceback: types.TracebackType | None = None, - ): + ) -> None: self.close() class ByteStream(Stream): - def __init__(self, data: bytes = b""): + def __init__(self, data: bytes = b"") -> None: self._buffer = io.BytesIO(data) self._size = len(data) @@ -40,7 +41,7 @@ def close(self) -> None: class FileStream(Stream): - def __init__(self, fileobj): + def __init__(self, fileobj: typing.BinaryIO) -> None: self._fileobj = fileobj def read(self, size: int = -1) -> bytes: @@ -52,19 +53,22 @@ def close(self) -> None: class MultiPartStream(Stream): def __init__( - self, form: list[tuple[str, str]], files: list[tuple[str, str]], boundary="" - ): + self, + form: list[tuple[str, str]], + files: list[tuple[str, str]], + boundary: str = "", + ) -> None: self._form = list(form) self._files = list(files) self._boundary = boundary or os.urandom(16).hex() # Mutable state... self._form_progress = list(self._form) self._files_progress = list(self._files) - self._fileobj: io.IOBase | None = None + self._fileobj: typing.BinaryIO | None = None self._complete = False self._buffer = io.BytesIO() - def read(self, size=-1) -> bytes: + def read(self, size: int = -1) -> bytes: sections = [] length = 0 diff --git a/src/hip/core/urlencode.py b/src/hip/core/urlencode.py index 3236e7a..60e5dab 100644 --- a/src/hip/core/urlencode.py +++ b/src/hip/core/urlencode.py @@ -7,8 +7,8 @@ SAFE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~" -def urlencode(multidict, safe=SAFE): - pairs = [] +def urlencode(multidict: dict[str, list[str]], safe: str = SAFE) -> str: + pairs: list[tuple[str, str]] = [] for key, values in multidict.items(): pairs.extend([(key, value) for value in values]) @@ -18,19 +18,19 @@ def urlencode(multidict, safe=SAFE): return "&".join(f"{quote(key, safe)}={quote(val, safe)}" for key, val in pairs) -def urldecode(string): +def urldecode(string: str) -> dict[str, list[str]]: parts = [part.partition("=") for part in string.split("&") if part] pairs = [(unquote(key), unquote(val)) for key, _, val in parts] pairs = [(k.replace("+", " "), v.replace("+", " ")) for k, v in pairs] - ret = {} + ret: dict[str, list[str]] = {} for k, v in pairs: ret.setdefault(k, []).append(v) return ret -def quote(string, safe=SAFE): +def quote(string: str, safe: str = SAFE) -> str: # Fast path if the string is already safe. if not string.strip(safe): return string @@ -39,7 +39,7 @@ def quote(string, safe=SAFE): return "".join([char if char in safe else percent(char) for char in string]) -def unquote(string): +def unquote(string: str) -> str: # Fast path if the string is not quoted. if "%" not in string: return string @@ -69,5 +69,5 @@ def unquote(string): return "".join(parts) -def percent(c): - return "".join(f"%{b:02X}" for b in c.encode("utf-8")) +def percent(char: str) -> str: + return "".join(f"%{b:02X}" for b in char.encode("utf-8")) diff --git a/src/hip/core/urlparse.py b/src/hip/core/urlparse.py index 8265213..7af6679 100644 --- a/src/hip/core/urlparse.py +++ b/src/hip/core/urlparse.py @@ -377,7 +377,7 @@ def encode_host(host: str) -> str: elif not host.isascii(): try: - import idna # type: ignore + import idna except ImportError: raise InvalidURL( f"Cannot handle URL with IDNA hostname: {host!r}. " From 3977bc7a84d2d45fdddb9d4bf5c240016313abe7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=87a=C4=9F=C4=B1l=20Ulu=C5=9Fahin?= Date: Tue, 1 Dec 2026 20:39:24 +0000 Subject: [PATCH 3/3] Edit mypy configuration for a stricter type checking --- .pre-commit-config.yaml | 2 +- pyproject.toml | 22 ++++++++++++++++++++++ scripts/check | 2 +- src/hip/backends/trio.py | 4 +++- tests/test_headers.py | 3 ++- tests/test_urls.py | 3 ++- 6 files changed, 31 insertions(+), 5 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 1db40b7..2c3867e 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -3,7 +3,7 @@ repos: hooks: - id: mypy name: Mypy - entry: uv run --no-sync mypy src + entry: uv run --no-sync mypy src tests language: system types: [python] pass_filenames: false diff --git a/pyproject.toml b/pyproject.toml index 623f35a..7fc64b9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -32,3 +32,25 @@ dev = [ [build-system] requires = ["uv_build>=0.13.0,<0.14.0"] build-backend = "uv_build" + +[tool.mypy] +strict = true + +[[tool.mypy.overrides]] +module = "tests.*" +disallow_untyped_defs = false +check_untyped_defs = true + +[[tool.mypy.overrides]] +module = [ + "hip.client.*", + "hip.server.*", + "hip.parsers.*", + "tests.test_client", + "tests.test_server", + "tests.test_pool", + "tests.test_network", + "tests.test_parsers", + "tests.parsers.*", +] +ignore_errors = true diff --git a/scripts/check b/scripts/check index 6d48adb..d917f96 100755 --- a/scripts/check +++ b/scripts/check @@ -1,3 +1,3 @@ #!/bin/sh -e -uv run --no-sync mypy src +uv run --no-sync mypy src tests diff --git a/src/hip/backends/trio.py b/src/hip/backends/trio.py index bc4475b..8a74482 100644 --- a/src/hip/backends/trio.py +++ b/src/hip/backends/trio.py @@ -130,7 +130,9 @@ async def __aexit__( ) -> bool | None: self._nursery.cancel_scope.cancel() try: - return await self._nursery_context.__aexit__(exc_type, exc_value, traceback) + return await self._nursery_context.__aexit__( # type: ignore[no-any-return] + exc_type, exc_value, traceback + ) finally: with trio.CancelScope(shield=True): for listener in self._listeners: diff --git a/tests/test_headers.py b/tests/test_headers.py index 2975871..f2c652b 100644 --- a/tests/test_headers.py +++ b/tests/test_headers.py @@ -116,7 +116,8 @@ def test_header_invalid_value(): def test_header_empty_value(): with pytest.raises(ValueError): - hip.Headers({""}) + # Test runtime validation of an invalid headers type. + hip.Headers({""}) # type: ignore[arg-type] def test_headers_not_equal_to_unrelated_type(): diff --git a/tests/test_urls.py b/tests/test_urls.py index ced6d25..c250265 100644 --- a/tests/test_urls.py +++ b/tests/test_urls.py @@ -102,7 +102,8 @@ def test_url_constructor_accepts_byte_query(): def test_url_rejects_invalid_type(): msg = "Invalid type for url. Expected str or hip.URL, got : 123" with pytest.raises(TypeError, match=msg): - hip.URL(123) + # Test runtime validation of an invalid URL type. + hip.URL(123) # type: ignore[arg-type] def test_url_target_includes_query():