Fix usage of `mypy --python-version=3.9` and friends
Marco Ricci

Marco Ricci commited on 2025-01-16 01:28:57
Zeige 3 geänderte Dateien mit 18 Einfügungen und 3 Löschungen.


On the one hand, use a small stub file for `tomli`, because `mypy` is
run from all sorts of `hatch` environments or Python virtual
environments that are not set up correctly with `tomli`.

On the other hand, type checking cannot rely on
`try`-`except`-`ImportError` blocks working for type inference purposes,
so variables imported as such need an explicit declaration.  (In this
specific case, this could be alleviated with explicit Python version
checks, but I find that decidedly unpythonic.)
... ...
@@ -0,0 +1,14 @@
1
+# SPDX-FileCopyrightText: 2025 Marco Ricci <software@the13thletter.info>
2
+#
3
+# SPDX-License-Identifier: Zlib
4
+#
5
+# Minimal stub file for the part of the tomli package we actually use.
6
+# Included here so that mypy will find the stubs regardless of whether
7
+# the correct hatch environment is used.
8
+
9
+from collections.abc import Callable
10
+from typing import IO, Any
11
+
12
+def load(
13
+    __fp: IO[bytes], /, *, parse_float: Callable[..., Any] = ...
14
+) -> dict[str, Any]: ...
... ...
@@ -185,7 +185,7 @@ path = "src/derivepassphrase/__init__.py"
185 185
 
186 186
 [tool.mypy]
187 187
 files = ['src/**/*.py', 'tests/**/*.py']
188
-mypy_path = '$MYPY_CONFIG_FILE_DIR/src'
188
+mypy_path = '$MYPY_CONFIG_FILE_DIR/src:$MYPY_CONFIG_FILE_DIR/other-stubs'
189 189
 explicit_package_bases = true
190 190
 implicit_reexport = false
191 191
 sqlite_cache = true
... ...
@@ -32,6 +32,7 @@ __all__ = ()
32 32
 if TYPE_CHECKING:
33 33
     import socket
34 34
     from collections.abc import Callable, Iterator, Mapping, Sequence
35
+    from contextlib import AbstractContextManager
35 36
 
36 37
     import click.testing
37 38
     from typing_extensions import Any
... ...
@@ -1478,10 +1479,10 @@ def isolated_vault_exporter_config(
1478 1479
     vault_key: str | None = None,
1479 1480
 ) -> Iterator[None]:
1480 1481
     if TYPE_CHECKING:
1481
-        chdir = contextlib.chdir
1482
+        chdir: Callable[..., AbstractContextManager]
1482 1483
     else:
1483 1484
         try:
1484
-            chdir = contextlib.chdir
1485
+            chdir = contextlib.chdir  # type: ignore[attr]
1485 1486
         except AttributeError:
1486 1487
 
1487 1488
             @contextlib.contextmanager
1488 1489