]> git.ipfire.org Git - thirdparty/psycopg.git/commitdiff
lint: add typing annotations to pass pre-commit
authorDaniele Varrazzo <daniele.varrazzo@gmail.com>
Fri, 27 Dec 2024 02:30:28 +0000 (03:30 +0100)
committerDaniele Varrazzo <daniele.varrazzo@gmail.com>
Fri, 27 Dec 2024 03:42:00 +0000 (04:42 +0100)
Pre-commit seems to run mypy in parallel batches, each with about 20
files. In this mode, certain tests that pass when running mypy all in
once or file-by-file, fail.

In the current state, both running mypy without arguments or running it
in pre-commit seem to work.

.pre-commit-config.yaml
psycopg/psycopg/_cmodule.py
psycopg/psycopg/_connection_base.py
psycopg/psycopg/_copy_base.py
psycopg/psycopg/_cursor_base.py
pyproject.toml
tests/scripts/pipeline-demo.py
tests/test_adapt.py
tests/types/test_array.py

index 06cacf82da453687a2397a0ac97c835419df3771..329b09d4f8d4b85a25c44b64d0c0a3ef7cd45af6 100644 (file)
@@ -22,5 +22,5 @@ repos:
       - id: mypy
         name: mypy
         language: system
-        entry: mypy --pretty
+        entry: mypy --pretty --follow-imports=silent
         files: \.py[i]?$
index 33162bc10b2dc69c13b3ad2d1db074cd8caf2f0b..b3abf12fd18362537181b62fdda3208c9294375d 100644 (file)
@@ -1,3 +1,4 @@
+# mypy: disable-error-code="import-not-found, attr-defined"
 """
 Simplify access to the _psycopg module
 """
@@ -6,19 +7,29 @@ Simplify access to the _psycopg module
 
 from __future__ import annotations
 
+from types import ModuleType
 from . import pq
 
 __version__: str | None = None
+_psycopg: ModuleType
 
 # Note: "c" must the first attempt so that mypy associates the variable the
 # right module interface. It will not result Optional, but hey.
 if pq.__impl__ == "c":
-    from psycopg_c import _psycopg as _psycopg
-    from psycopg_c import __version__ as __version__  # noqa: F401
+    import psycopg_c._psycopg
+
+    _psycopg = psycopg_c._psycopg
+    __version__ = psycopg_c.__version__
+
 elif pq.__impl__ == "binary":
-    from psycopg_binary import _psycopg as _psycopg  # type: ignore
-    from psycopg_binary import __version__ as __version__  # type: ignore  # noqa: F401
+    import psycopg_binary._psycopg
+
+    _psycopg = psycopg_binary._psycopg
+    __version__ = psycopg_binary.__version__
+
 elif pq.__impl__ == "python":
-    _psycopg = None  # type: ignore
+
+    _psycopg = None  # type: ignore[assignment]
+
 else:
     raise ImportError(f"can't find _psycopg optimised module in {pq.__impl__!r}")
index ab34a7cc0b8934c67aa14ebd88d3b9a7feae551e..90cd237caecc9d6af2f906fe38dd81c945dce520 100644 (file)
@@ -482,7 +482,7 @@ class BaseConnection(Generic[Row]):
         else:
             self.pgconn.send_query_params(command, None, result_format=result_format)
 
-        result = (yield from generators.execute(self.pgconn))[-1]
+        result: PGresult = (yield from generators.execute(self.pgconn))[-1]
         if result.status != COMMAND_OK and result.status != TUPLES_OK:
             if result.status == FATAL_ERROR:
                 raise e.error_from_result(result, encoding=self.pgconn._encoding)
index 9217a90e1e80878b4e8b36fbb3f210b296b7ee43..21608c9728d80d7f002111ffadcf1059d5e799a5 100644 (file)
@@ -216,10 +216,11 @@ class TextFormatter(Formatter):
         self._encoding = encoding
 
     def parse_row(self, data: Buffer) -> tuple[Any, ...] | None:
+        rv: tuple[Any, ...] | None = None
         if data:
-            return parse_row_text(data, self.transformer)
-        else:
-            return None
+            rv = parse_row_text(data, self.transformer)
+
+        return rv
 
     def write(self, buffer: Buffer | str) -> Buffer:
         data = self._ensure_bytes(buffer)
@@ -260,6 +261,8 @@ class BinaryFormatter(Formatter):
         self._signature_sent = False
 
     def parse_row(self, data: Buffer) -> tuple[Any, ...] | None:
+        rv: tuple[Any, ...] | None = None
+
         if not self._signature_sent:
             if data[: len(_binary_signature)] != _binary_signature:
                 raise e.DataError(
@@ -268,10 +271,10 @@ class BinaryFormatter(Formatter):
             self._signature_sent = True
             data = data[len(_binary_signature) :]
 
-        elif data == _binary_trailer:
-            return None
+        if data != _binary_trailer:
+            rv = parse_row_binary(data, self.transformer)
 
-        return parse_row_binary(data, self.transformer)
+        return rv
 
     def write(self, buffer: Buffer | str) -> Buffer:
         data = self._ensure_bytes(buffer)
index e09f17ab07d97a12887959206e4a132d71e2c670..45b6006744afa44b0c1a000d01aa3b11b99fe01e 100644 (file)
@@ -334,7 +334,7 @@ class BaseCursor(Generic[ConnectionType, Row]):
         yield from send(self._pgconn)
 
     def _stream_fetchone_gen(self, first: bool) -> PQGen[PGresult | None]:
-        res = yield from fetch(self._pgconn)
+        res: PGresult | None = yield from fetch(self._pgconn)
         if res is None:
             return None
 
index 4e76bc8e648de0e1bf2adfd8e38ede586dce1eeb..ce539c1d41757ccd6316a0e6ad5bd5e3f126d81b 100644 (file)
@@ -50,6 +50,7 @@ exclude = '''(?x)(
 [[tool.mypy.overrides]]
 module = [
     "numpy.*",
+    "polib",
     "shapely.*",
 ]
 ignore_missing_imports = true
index 1d44e4070606ff5762f6f9ea0a9261ecafaa9b92..8f44e15e07564c0be358c97d59cac32c30793170 100644 (file)
@@ -190,10 +190,7 @@ def pipeline_demo_pq(rows_to_send: int, logger: logging.Logger) -> None:
     ):
         while results_queue:
             fetched = waiting.wait(
-                pipeline_communicate(
-                    pgconn,  # type: ignore[arg-type]
-                    commands,
-                ),
+                pipeline_communicate(pgconn, commands),
                 pgconn.socket,
             )
             assert not commands, commands
@@ -216,10 +213,7 @@ async def pipeline_demo_pq_async(rows_to_send: int, logger: logging.Logger) -> N
     ):
         while results_queue:
             fetched = await waiting.wait_async(
-                pipeline_communicate(
-                    pgconn,  # type: ignore[arg-type]
-                    commands,
-                ),
+                pipeline_communicate(pgconn, commands),
                 pgconn.socket,
             )
             assert not commands, commands
index 376f0de268b1fb22f7dffaec01e80d88a2a43bed..49f9c46ecd04c8f09d94fa33fb1a1be4b56778ab 100644 (file)
@@ -427,10 +427,7 @@ def test_optimised_adapters():
         obj = getattr(_psycopg, n)
         if not isinstance(obj, type):
             continue
-        if not issubclass(
-            obj,
-            (_psycopg.CDumper, _psycopg.CLoader),  # type: ignore[attr-defined]
-        ):
+        if not issubclass(obj, (_psycopg.CDumper, _psycopg.CLoader)):
             continue
         c_adapters[n] = obj
 
index 7831a15ebf3afc00cfeddcd35a28c714ae2636cf..c1df5dae5e4f6b2bbd457fa163cfb4b7d3ce2f41 100644 (file)
@@ -8,6 +8,7 @@ from decimal import Decimal
 import pytest
 
 import psycopg
+import psycopg.types.numeric
 from psycopg import pq
 from psycopg import sql
 from psycopg.adapt import PyFormat, Transformer, Dumper