]> git.ipfire.org Git - thirdparty/psycopg.git/commitdiff
refactor: avoid using types as strings where possible
authorDaniele Varrazzo <daniele.varrazzo@gmail.com>
Thu, 30 May 2024 02:14:17 +0000 (04:14 +0200)
committerDaniele Varrazzo <daniele.varrazzo@gmail.com>
Tue, 4 Jun 2024 14:52:16 +0000 (16:52 +0200)
38 files changed:
psycopg/psycopg/_adapters_map.py
psycopg/psycopg/_column.py
psycopg/psycopg/_connection_base.py
psycopg/psycopg/_copy.py
psycopg/psycopg/_copy_async.py
psycopg/psycopg/_copy_base.py
psycopg/psycopg/_cursor_base.py
psycopg/psycopg/_encodings.py
psycopg/psycopg/_pipeline.py
psycopg/psycopg/_preparing.py
psycopg/psycopg/_py_transformer.py
psycopg/psycopg/_queries.py
psycopg/psycopg/abc.py
psycopg/psycopg/adapt.py
psycopg/psycopg/client_cursor.py
psycopg/psycopg/connection.py
psycopg/psycopg/connection_async.py
psycopg/psycopg/crdb/connection.py
psycopg/psycopg/cursor.py
psycopg/psycopg/cursor_async.py
psycopg/psycopg/errors.py
psycopg/psycopg/pq/_debug.py
psycopg/psycopg/pq/abc.py
psycopg/psycopg/pq/pq_ctypes.py
psycopg/psycopg/raw_cursor.py
psycopg/psycopg/rows.py
psycopg/psycopg/server_cursor.py
psycopg/psycopg/transaction.py
psycopg/psycopg/types/composite.py
psycopg/psycopg/types/datetime.py
psycopg/psycopg/types/enum.py
psycopg/psycopg/types/multirange.py
psycopg/psycopg/types/range.py
psycopg/psycopg/types/string.py
psycopg/psycopg/types/uuid.py
psycopg_c/psycopg_c/pq/pgconn.pyx
psycopg_pool/psycopg_pool/abc.py
psycopg_pool/psycopg_pool/base.py

index 55a3cf1e4c5b83229c7e7cbc7bf301567918d549..53e1b583b94704b93b54bb9b75297dde7312e777 100644 (file)
@@ -70,7 +70,7 @@ class AdaptersMap:
 
     def __init__(
         self,
-        template: "AdaptersMap" | None = None,
+        template: AdaptersMap | None = None,
         types: TypesRegistry | None = None,
     ):
         if template:
@@ -102,11 +102,11 @@ class AdaptersMap:
 
     # implement the AdaptContext protocol too
     @property
-    def adapters(self) -> "AdaptersMap":
+    def adapters(self) -> AdaptersMap:
         return self
 
     @property
-    def connection(self) -> "BaseConnection[Any]" | None:
+    def connection(self) -> BaseConnection[Any] | None:
         return None
 
     def register_dumper(self, cls: type | str | None, dumper: type[Dumper]) -> None:
index 2e441b678811d64cdbea1ba066a9e15cbf3559d6..92973824ec68b2b0d305be85c954563de6af1579 100644 (file)
@@ -16,7 +16,7 @@ if TYPE_CHECKING:
 class Column(Sequence[Any]):
     __module__ = "psycopg"
 
-    def __init__(self, cursor: "BaseCursor[Any, Any]", index: int):
+    def __init__(self, cursor: BaseCursor[Any, Any], index: int):
         res = cursor.pgresult
         assert res
 
index 691969b819d94182704f80f229d595d50badbe59..8b0277dadf6f4e70de41deac6c59b0935b1712a3 100644 (file)
@@ -99,7 +99,7 @@ class BaseConnection(Generic[Row]):
     ConnStatus = pq.ConnStatus
     TransactionStatus = pq.TransactionStatus
 
-    def __init__(self, pgconn: "PGconn"):
+    def __init__(self, pgconn: PGconn):
         self.pgconn = pgconn
         self._autocommit = False
 
@@ -122,7 +122,7 @@ class BaseConnection(Generic[Row]):
 
         # Attribute is only set if the connection is from a pool so we can tell
         # apart a connection in the pool too (when _pool = None)
-        self._pool: "BasePool" | None
+        self._pool: BasePool | None
 
         self._pipeline: BasePipeline | None = None
 
@@ -337,7 +337,7 @@ class BaseConnection(Generic[Row]):
 
     @staticmethod
     def _notice_handler(
-        wself: "ReferenceType[BaseConnection[Row]]", res: "PGresult"
+        wself: "ReferenceType[BaseConnection[Row]]", res: PGresult
     ) -> None:
         self = wself()
         if not (self and self._notice_handlers):
@@ -437,7 +437,7 @@ class BaseConnection(Generic[Row]):
 
     def _exec_command(
         self, command: Query, result_format: pq.Format = TEXT
-    ) -> PQGen["PGresult" | None]:
+    ) -> PQGen[PGresult | None]:
         """
         Generator to send a command and receive the result to the backend.
 
index 1c393a9d632925f4ab4079930a3683d0b071bfef..092d9635aeb31d20a54f5c4ff43e51ffce07e224 100644 (file)
@@ -24,7 +24,7 @@ from ._acompat import spawn, gather, Queue, Worker
 if TYPE_CHECKING:
     from .abc import Buffer
     from .cursor import Cursor
-    from .connection import Connection  # noqa: F401
+    from .connection import Connection
 
 COPY_IN = pq.ExecStatus.COPY_IN
 COPY_OUT = pq.ExecStatus.COPY_OUT
@@ -32,7 +32,7 @@ COPY_OUT = pq.ExecStatus.COPY_OUT
 ACTIVE = pq.TransactionStatus.ACTIVE
 
 
-class Copy(BaseCopy["Connection[Any]"]):
+class Copy(BaseCopy[Connection[Any]]):
     """Manage an asynchronous :sql:`COPY` operation.
 
     :param cursor: the cursor where the operation is performed.
index 2c630da9b96d7b12d7c56d46f660e4de41b521dd..6cddac413592e45c9f8866b3a1ea49b748fb8d3b 100644 (file)
@@ -21,7 +21,7 @@ from ._acompat import aspawn, agather, AQueue, AWorker
 if TYPE_CHECKING:
     from .abc import Buffer
     from .cursor_async import AsyncCursor
-    from .connection_async import AsyncConnection  # noqa: F401
+    from .connection_async import AsyncConnection
 
 COPY_IN = pq.ExecStatus.COPY_IN
 COPY_OUT = pq.ExecStatus.COPY_OUT
@@ -29,7 +29,7 @@ COPY_OUT = pq.ExecStatus.COPY_OUT
 ACTIVE = pq.TransactionStatus.ACTIVE
 
 
-class AsyncCopy(BaseCopy["AsyncConnection[Any]"]):
+class AsyncCopy(BaseCopy[AsyncConnection[Any]]):
     """Manage an asynchronous :sql:`COPY` operation.
 
     :param cursor: the cursor where the operation is performed.
index 354b589e49708dfd6627f4ed44e484fc16bb40ee..d3a143c5f5cc8167eea39d6a99b612eee7f332d9 100644 (file)
@@ -23,8 +23,6 @@ from .generators import copy_from
 
 if TYPE_CHECKING:
     from ._cursor_base import BaseCursor
-    from .connection import Connection  # noqa: F401
-    from .connection_async import AsyncConnection  # noqa: F401
 
 PY_TEXT = adapt.PyFormat.TEXT
 PY_BINARY = adapt.PyFormat.BINARY
@@ -77,7 +75,7 @@ class BaseCopy(Generic[ConnectionType]):
 
     def __init__(
         self,
-        cursor: "BaseCursor[ConnectionType, Any]",
+        cursor: BaseCursor[ConnectionType, Any],
         *,
         binary: bool | None = None,
     ):
index 6fb08dcfa8ac9948416276f944425306caedd2fc..1f223451339f6dbff58d153000a19fcc167c5395 100644 (file)
@@ -52,9 +52,9 @@ class BaseCursor(Generic[ConnectionType, Row]):
 
     ExecStatus = pq.ExecStatus
 
-    _tx: "Transformer"
+    _tx: Transformer
     _make_row: RowMaker[Row]
-    _pgconn: "PGconn"
+    _pgconn: PGconn
     _query_cls: type[PostgresQuery] = PostgresQuery
 
     def __init__(self, connection: ConnectionType):
@@ -68,8 +68,8 @@ class BaseCursor(Generic[ConnectionType, Row]):
         self._reset()
 
     def _reset(self, reset_query: bool = True) -> None:
-        self._results: list["PGresult"] = []
-        self.pgresult: "PGresult" | None = None
+        self._results: list[PGresult] = []
+        self.pgresult: PGresult | None = None
         self._pos = 0
         self._iresult = 0
         self._rowcount = -1
@@ -324,7 +324,7 @@ class BaseCursor(Generic[ConnectionType, Row]):
         self._last_query = query
         yield from send(self._pgconn)
 
-    def _stream_fetchone_gen(self, first: bool) -> PQGen["PGresult" | None]:
+    def _stream_fetchone_gen(self, first: bool) -> PQGen[PGresult | None]:
         res = yield from fetch(self._pgconn)
         if res is None:
             return None
@@ -446,7 +446,7 @@ class BaseCursor(Generic[ConnectionType, Row]):
         pgq.convert(query, params)
         return pgq
 
-    def _check_results(self, results: list["PGresult"]) -> None:
+    def _check_results(self, results: list[PGresult]) -> None:
         """
         Verify that the results of a query are valid.
 
@@ -461,7 +461,7 @@ class BaseCursor(Generic[ConnectionType, Row]):
             if status != TUPLES_OK and status != COMMAND_OK and status != EMPTY_QUERY:
                 self._raise_for_result(res)
 
-    def _raise_for_result(self, result: "PGresult") -> NoReturn:
+    def _raise_for_result(self, result: PGresult) -> NoReturn:
         """
         Raise an appropriate error message for an unexpected database result
         """
@@ -505,7 +505,7 @@ class BaseCursor(Generic[ConnectionType, Row]):
 
         self._make_row = self._make_row_maker()
 
-    def _set_results(self, results: list["PGresult"]) -> None:
+    def _set_results(self, results: list[PGresult]) -> None:
         if self._execmany_returning is None:
             # Received from execute()
             self._results[:] = results
@@ -578,7 +578,7 @@ class BaseCursor(Generic[ConnectionType, Row]):
         else:
             raise e.ProgrammingError("the last operation didn't produce a result")
 
-    def _check_copy_result(self, result: "PGresult") -> None:
+    def _check_copy_result(self, result: PGresult) -> None:
         """
         Check that the value returned in a copy() operation is a legit COPY.
         """
index a6c0ac4c4b4b972ca5ddc4ebea85d00d1eac4900..b515f96fd734b71b8aa8bb6b7b62b5d6f6504b47 100644 (file)
@@ -80,7 +80,7 @@ py_codecs.update(
 pg_codecs = {v: k.encode() for k, v in _py_codecs.items()}
 
 
-def conn_encoding(conn: "BaseConnection[Any] | None") -> str:
+def conn_encoding(conn: BaseConnection[Any] | None) -> str:
     """
     Return the Python encoding name of a psycopg connection.
 
@@ -92,7 +92,7 @@ def conn_encoding(conn: "BaseConnection[Any] | None") -> str:
         return "utf-8"
 
 
-def pgconn_encoding(pgconn: "PGconn") -> str:
+def pgconn_encoding(pgconn: PGconn) -> str:
     """
     Return the Python encoding name of a libpq connection.
 
index 239b619b562c96a08ccb440d61be07541c500788..9b64572180f544edf181944d01b2406f58b240fa 100644 (file)
@@ -45,7 +45,7 @@ class BasePipeline:
     command_queue: Deque[PipelineCommand]
     result_queue: Deque[PendingResult]
 
-    def __init__(self, conn: "BaseConnection[Any]") -> None:
+    def __init__(self, conn: BaseConnection[Any]) -> None:
         self._conn = conn
         self.pgconn = conn.pgconn
         self.command_queue = Deque[PipelineCommand]()
@@ -157,9 +157,7 @@ class BasePipeline:
         if exception is not None:
             raise exception
 
-    def _process_results(
-        self, queued: PendingResult, results: list["PGresult"]
-    ) -> None:
+    def _process_results(self, queued: PendingResult, results: list[PGresult]) -> None:
         """Process a results set fetched from the current pipeline.
 
         This matches 'results' with its respective element in the pipeline
@@ -192,9 +190,9 @@ class Pipeline(BasePipeline):
     """Handler for connection in pipeline mode."""
 
     __module__ = "psycopg"
-    _conn: "Connection[Any]"
+    _conn: Connection[Any]
 
-    def __init__(self, conn: "Connection[Any]") -> None:
+    def __init__(self, conn: Connection[Any]) -> None:
         super().__init__(conn)
 
     def sync(self) -> None:
@@ -235,9 +233,9 @@ class AsyncPipeline(BasePipeline):
     """Handler for async connection in pipeline mode."""
 
     __module__ = "psycopg"
-    _conn: "AsyncConnection[Any]"
+    _conn: AsyncConnection[Any]
 
-    def __init__(self, conn: "AsyncConnection[Any]") -> None:
+    def __init__(self, conn: AsyncConnection[Any]) -> None:
         super().__init__(conn)
 
     async def sync(self) -> None:
index eccf260de1a83271be69d85a59e95340a8d21da2..4face76876d0a821ed212ea5ab2cc7afb196531e 100644 (file)
@@ -7,7 +7,7 @@ Support for prepared statements
 from __future__ import annotations
 
 from enum import IntEnum, auto
-from typing import Sequence, TYPE_CHECKING
+from typing import Any, Sequence, TYPE_CHECKING
 from collections import OrderedDict
 
 from . import pq
@@ -16,7 +16,6 @@ from ._compat import Deque, TypeAlias
 from ._queries import PostgresQuery
 
 if TYPE_CHECKING:
-    from typing import Any
     from .pq.abc import PGresult
     from ._connection_base import BaseConnection
 
@@ -81,7 +80,7 @@ class PrepareManager:
             # The query is not to be prepared yet
             return Prepare.NO, b""
 
-    def _should_discard(self, prep: Prepare, results: Sequence["PGresult"]) -> bool:
+    def _should_discard(self, prep: Prepare, results: Sequence[PGresult]) -> bool:
         """Check if we need to discard our entire state: it should happen on
         rollback or on dropping objects, because the same object may get
         recreated and postgres would fail internal lookups.
@@ -96,7 +95,7 @@ class PrepareManager:
         return False
 
     @staticmethod
-    def _check_results(results: Sequence["PGresult"]) -> bool:
+    def _check_results(results: Sequence[PGresult]) -> bool:
         """Return False if 'results' are invalid for prepared statement cache."""
         if len(results) != 1:
             # We cannot prepare a multiple statement
@@ -160,7 +159,7 @@ class PrepareManager:
         key: Key,
         prep: Prepare,
         name: bytes,
-        results: Sequence["PGresult"],
+        results: Sequence[PGresult],
     ) -> None:
         """Validate cached entry with 'key' by checking query 'results'.
 
@@ -190,7 +189,7 @@ class PrepareManager:
         else:
             return False
 
-    def maintain_gen(self, conn: "BaseConnection[Any]") -> PQGen[None]:
+    def maintain_gen(self, conn: BaseConnection[Any]) -> PQGen[None]:
         """
         Generator to send the commands to perform periodic maintenance
 
index 3a1c2e5ab03533cc886e1122067d53355271dfa7..c2f4ea21cc5eea775a586dbfb6ad9f8ac05fd343 100644 (file)
@@ -58,8 +58,8 @@ class Transformer(AdaptContext):
     types: tuple[int, ...] | None
     formats: list[pq.Format] | None
 
-    _adapters: "AdaptersMap"
-    _pgresult: "PGresult" | None
+    _adapters: AdaptersMap
+    _pgresult: PGresult | None
     _none_oid: int
 
     def __init__(self, context: AdaptContext | None = None):
@@ -111,7 +111,7 @@ class Transformer(AdaptContext):
             return cls(context)
 
     @property
-    def connection(self) -> "BaseConnection[Any]" | None:
+    def connection(self) -> BaseConnection[Any] | None:
         return self._conn
 
     @property
@@ -121,16 +121,16 @@ class Transformer(AdaptContext):
         return self._encoding
 
     @property
-    def adapters(self) -> "AdaptersMap":
+    def adapters(self) -> AdaptersMap:
         return self._adapters
 
     @property
-    def pgresult(self) -> "PGresult" | None:
+    def pgresult(self) -> PGresult | None:
         return self._pgresult
 
     def set_pgresult(
         self,
-        result: "PGresult" | None,
+        result: PGresult | None,
         *,
         set_loaders: bool = True,
         format: pq.Format | None = None,
index 517ed7af9bbefb1b6c6e594d6a8ec9faf35ebe09..0cd615b6a3e0e9d8d635a7e0f5f59e19a2d9fd23 100644 (file)
@@ -42,7 +42,7 @@ class PostgresQuery:
         _tx _want_formats _parts _encoding _order
         """.split()
 
-    def __init__(self, transformer: "Transformer"):
+    def __init__(self, transformer: Transformer):
         self._tx = transformer
 
         self.params: Sequence[Buffer | None] | None = None
index 6eef150813da1bcb14817f88b6988770a8a36c47..e5e02d7e6e55d2e08e1ba7a82b7eed662ea22617 100644 (file)
@@ -14,7 +14,7 @@ from ._enums import PyFormat as PyFormat
 from ._compat import LiteralString, TypeAlias, TypeVar
 
 if TYPE_CHECKING:
-    from . import sql  # noqa: F401
+    from . import sql
     from .rows import Row, RowMaker
     from .pq.abc import PGresult
     from .waiting import Wait, Ready
@@ -26,7 +26,7 @@ NoneType: type = type(None)
 # An object implementing the buffer protocol
 Buffer: TypeAlias = bytes | bytearray | memoryview
 
-Query: TypeAlias = LiteralString | bytes | "sql.SQL" | "sql.Composed"
+Query: TypeAlias = LiteralString | bytes | sql.SQL | sql.Composed
 Params: TypeAlias = Sequence[Any] | Mapping[str, Any]
 ConnectionType = TypeVar("ConnectionType", bound="BaseConnection[Any]")
 PipelineCommand: TypeAlias = Callable[[], None]
@@ -46,7 +46,7 @@ PQGenConn: TypeAlias = Generator[tuple[int, Wait], Ready | int, RV]
 This can happen in connection and reset, but not in normal querying.
 """
 
-PQGen: TypeAlias = Generator["Wait", "Ready" | int, RV]
+PQGen: TypeAlias = Generator[Wait, Ready | int, RV]
 """Generator for processes where the connection file number won't change.
 """
 
@@ -80,12 +80,12 @@ class AdaptContext(Protocol):
     """
 
     @property
-    def adapters(self) -> "AdaptersMap":
+    def adapters(self) -> AdaptersMap:
         """The adapters configuration that this object uses."""
         ...
 
     @property
-    def connection(self) -> "BaseConnection[Any]" | None:
+    def connection(self) -> BaseConnection[Any] | None:
         """The connection used by this object, if available.
 
         :rtype: `~psycopg.Connection` or `~psycopg.AsyncConnection` or `!None`
@@ -161,7 +161,7 @@ class Dumper(Protocol):
         """
         ...
 
-    def upgrade(self, obj: Any, format: PyFormat) -> "Dumper":
+    def upgrade(self, obj: Any, format: PyFormat) -> Dumper:
         """Return a new dumper to manage `!obj`.
 
         :param obj: The object to convert
@@ -207,23 +207,23 @@ class Transformer(Protocol):
     def __init__(self, context: AdaptContext | None = None): ...
 
     @classmethod
-    def from_context(cls, context: AdaptContext | None) -> "Transformer": ...
+    def from_context(cls, context: AdaptContext | None) -> Transformer: ...
 
     @property
-    def connection(self) -> "BaseConnection[Any]" | None: ...
+    def connection(self) -> BaseConnection[Any] | None: ...
 
     @property
     def encoding(self) -> str: ...
 
     @property
-    def adapters(self) -> "AdaptersMap": ...
+    def adapters(self) -> AdaptersMap: ...
 
     @property
-    def pgresult(self) -> "PGresult" | None: ...
+    def pgresult(self) -> PGresult | None: ...
 
     def set_pgresult(
         self,
-        result: "PGresult" | None,
+        result: PGresult | None,
         *,
         set_loaders: bool = True,
         format: pq.Format | None = None,
@@ -241,11 +241,9 @@ class Transformer(Protocol):
 
     def get_dumper(self, obj: Any, format: PyFormat) -> Dumper: ...
 
-    def load_rows(
-        self, row0: int, row1: int, make_row: "RowMaker[Row]"
-    ) -> list["Row"]: ...
+    def load_rows(self, row0: int, row1: int, make_row: RowMaker[Row]) -> list[Row]: ...
 
-    def load_row(self, row: int, make_row: "RowMaker[Row]") -> "Row" | None: ...
+    def load_row(self, row: int, make_row: RowMaker[Row]) -> Row | None: ...
 
     def load_sequence(self, record: Sequence[Buffer | None]) -> tuple[Any, ...]: ...
 
index fa590332cf3dd8bff4cedfba3240f9af9b771d4f..889801de9b1fdcd7be8ef0d6890330ed592fa16e 100644 (file)
@@ -14,7 +14,7 @@ from . import pq, abc
 # Objects exported here
 from ._enums import PyFormat as PyFormat
 from ._transformer import Transformer as Transformer
-from ._adapters_map import AdaptersMap as AdaptersMap  # noqa: F401
+from ._adapters_map import AdaptersMap as AdaptersMap  # noqa: F401 # reexport
 
 if TYPE_CHECKING:
     from ._connection_base import BaseConnection
@@ -37,7 +37,7 @@ class Dumper(abc.Dumper, ABC):
 
     def __init__(self, cls: type, context: abc.AdaptContext | None = None):
         self.cls = cls
-        self.connection: "BaseConnection[Any]" | None
+        self.connection: BaseConnection[Any] | None
         self.connection = context.connection if context else None
 
     def __repr__(self) -> str:
@@ -128,7 +128,7 @@ class Loader(abc.Loader, ABC):
 
     def __init__(self, oid: int, context: abc.AdaptContext | None = None):
         self.oid = oid
-        self.connection: "BaseConnection[Any]" | None
+        self.connection: BaseConnection[Any] | None
         self.connection = context.connection if context else None
 
     @abstractmethod
index 5a64e5fe77b26ef88ef23b7edc125c7d81e1d9a0..058d0fe62a374c98669068dffc3291fd363443fe 100644 (file)
@@ -6,7 +6,7 @@ psycopg client-side binding cursors
 
 from __future__ import annotations
 
-from typing import TYPE_CHECKING
+from typing import Any, TYPE_CHECKING
 from functools import partial
 
 from ._queries import PostgresQuery, PostgresClientQuery
@@ -22,9 +22,8 @@ from ._cursor_base import BaseCursor
 from .cursor_async import AsyncCursor
 
 if TYPE_CHECKING:
-    from typing import Any  # noqa: F401
-    from .connection import Connection  # noqa: F401
-    from .connection_async import AsyncConnection  # noqa: F401
+    from .connection import Connection
+    from .connection_async import AsyncConnection
 
 TEXT = pq.Format.TEXT
 BINARY = pq.Format.BINARY
@@ -83,11 +82,9 @@ class ClientCursorMixin(BaseCursor[ConnectionType, Row]):
         return (Prepare.NO, b"")
 
 
-class ClientCursor(ClientCursorMixin["Connection[Any]", Row], Cursor[Row]):
+class ClientCursor(ClientCursorMixin[Connection[Any], Row], Cursor[Row]):
     __module__ = "psycopg"
 
 
-class AsyncClientCursor(
-    ClientCursorMixin["AsyncConnection[Any]", Row], AsyncCursor[Row]
-):
+class AsyncClientCursor(ClientCursorMixin[AsyncConnection[Any], Row], AsyncCursor[Row]):
     __module__ = "psycopg"
index c285add9e37e77f65174ef36edd263659229fa10..277d3ab7cd57bd89e41d778af396c6b7bd78a99b 100644 (file)
@@ -68,7 +68,7 @@ class Connection(BaseConnection[Row]):
 
     def __init__(
         self,
-        pgconn: "PGconn",
+        pgconn: PGconn,
         row_factory: RowFactory[Row] = cast(RowFactory[Row], tuple_row),
     ):
         super().__init__(pgconn)
index 12de50a5462594dde4c3f4ca94dc93e3c49fd043..d66f6fbf3f1567434c3887fb2913850d9cc4cda6 100644 (file)
@@ -74,7 +74,7 @@ class AsyncConnection(BaseConnection[Row]):
 
     def __init__(
         self,
-        pgconn: "PGconn",
+        pgconn: PGconn,
         row_factory: AsyncRowFactory[Row] = cast(AsyncRowFactory[Row], tuple_row),
     ):
         super().__init__(pgconn)
index 5792e6f6b410c25443435fe4ddd2cc3fc138b654..74b34a7db7073a227b2b7f922ed802e20ed53f34 100644 (file)
@@ -23,10 +23,10 @@ if TYPE_CHECKING:
 
 class _CrdbConnectionMixin:
     _adapters: AdaptersMap | None
-    pgconn: "PGconn"
+    pgconn: PGconn
 
     @classmethod
-    def is_crdb(cls, conn: Connection[Any] | AsyncConnection[Any] | "PGconn") -> bool:
+    def is_crdb(cls, conn: Connection[Any] | AsyncConnection[Any] | PGconn) -> bool:
         """
         Return `!True` if the server connected to `!conn` is CockroachDB.
         """
index 6d1ddf01928832237702d533297bbaf9c5cc4512..fdcd7e66e413cc82ab989745f9ae99106a940cdb 100644 (file)
@@ -28,7 +28,7 @@ if TYPE_CHECKING:
 ACTIVE = pq.TransactionStatus.ACTIVE
 
 
-class Cursor(BaseCursor["Connection[Any]", Row]):
+class Cursor(BaseCursor[Connection[Any], Row]):
     __module__ = "psycopg"
     __slots__ = ()
 
index b708d5d6c6960284831bc3124a2c9639fbd61aa6..c07fccc7f02f48c8016867862e36004f42a35f14 100644 (file)
@@ -25,7 +25,7 @@ if TYPE_CHECKING:
 ACTIVE = pq.TransactionStatus.ACTIVE
 
 
-class AsyncCursor(BaseCursor["AsyncConnection[Any]", Row]):
+class AsyncCursor(BaseCursor[AsyncConnection[Any], Row]):
     __module__ = "psycopg"
     __slots__ = ()
 
index 5d6472bba7e4095a6dfb9e5dae32fc569b257355..f6b1410c4a22670c0307e81364436a5fb29fba8b 100644 (file)
@@ -68,8 +68,8 @@ class FinishedPGconn:
 
     nonblocking: int = 0
 
-    notice_handler: Callable[["PGresult"], None] | None = None
-    notify_handler: Callable[["PGnotify"], None] | None = None
+    notice_handler: Callable[[PGresult], None] | None = None
+    notify_handler: Callable[[PGnotify], None] | None = None
 
     @staticmethod
     def _raise() -> NoReturn:
index bc888648acf160503566a0a3195af0983390da71..9d1d36389e10de36ef04304f61b1b7af6b2d5d7a 100644 (file)
@@ -48,9 +48,9 @@ logger = logging.getLogger("psycopg.debug")
 class PGconnDebug:
     """Wrapper for a PQconn logging all its access."""
 
-    _pgconn: "abc.PGconn"
+    _pgconn: abc.PGconn
 
-    def __init__(self, pgconn: "abc.PGconn"):
+    def __init__(self, pgconn: abc.PGconn):
         super().__setattr__("_pgconn", pgconn)
 
     def __repr__(self) -> str:
index 876a3f40879172fbc052682fc5beeb4e0cafceca..4bf350934d479ca17cb4cbdf6814ed6510b907cc 100644 (file)
@@ -9,7 +9,7 @@ from __future__ import annotations
 from typing import Any, Callable, Protocol, Sequence, TYPE_CHECKING
 
 from ._enums import Format, Trace
-from .._compat import TypeAlias
+from .._compat import Self, TypeAlias
 
 if TYPE_CHECKING:
     from .misc import PGnotify, ConninfoOption, PGresAttDesc
@@ -19,21 +19,21 @@ Buffer: TypeAlias = bytes | bytearray | memoryview
 
 
 class PGconn(Protocol):
-    notice_handler: Callable[["PGresult"], None] | None
-    notify_handler: Callable[["PGnotify"], None] | None
+    notice_handler: Callable[[PGresult], None] | None
+    notify_handler: Callable[[PGnotify], None] | None
 
     @classmethod
-    def connect(cls, conninfo: bytes) -> "PGconn": ...
+    def connect(cls, conninfo: bytes) -> Self: ...
 
     @classmethod
-    def connect_start(cls, conninfo: bytes) -> "PGconn": ...
+    def connect_start(cls, conninfo: bytes) -> Self: ...
 
     def connect_poll(self) -> int: ...
 
     def finish(self) -> None: ...
 
     @property
-    def info(self) -> list["ConninfoOption"]: ...
+    def info(self) -> list[ConninfoOption]: ...
 
     def reset(self) -> None: ...
 
@@ -97,7 +97,7 @@ class PGconn(Protocol):
     @property
     def ssl_in_use(self) -> bool: ...
 
-    def exec_(self, command: bytes) -> "PGresult": ...
+    def exec_(self, command: bytes) -> PGresult: ...
 
     def send_query(self, command: bytes) -> None: ...
 
@@ -108,7 +108,7 @@ class PGconn(Protocol):
         param_types: Sequence[int] | None = None,
         param_formats: Sequence[int] | None = None,
         result_format: int = Format.TEXT,
-    ) -> "PGresult": ...
+    ) -> PGresult: ...
 
     def send_query_params(
         self,
@@ -139,7 +139,7 @@ class PGconn(Protocol):
         name: bytes,
         command: bytes,
         param_types: Sequence[int] | None = None,
-    ) -> "PGresult": ...
+    ) -> PGresult: ...
 
     def exec_prepared(
         self,
@@ -147,25 +147,25 @@ class PGconn(Protocol):
         param_values: Sequence[Buffer] | None,
         param_formats: Sequence[int] | None = None,
         result_format: int = 0,
-    ) -> "PGresult": ...
+    ) -> PGresult: ...
 
-    def describe_prepared(self, name: bytes) -> "PGresult": ...
+    def describe_prepared(self, name: bytes) -> PGresult: ...
 
     def send_describe_prepared(self, name: bytes) -> None: ...
 
-    def describe_portal(self, name: bytes) -> "PGresult": ...
+    def describe_portal(self, name: bytes) -> PGresult: ...
 
     def send_describe_portal(self, name: bytes) -> None: ...
 
-    def close_prepared(self, name: bytes) -> "PGresult": ...
+    def close_prepared(self, name: bytes) -> PGresult: ...
 
     def send_close_prepared(self, name: bytes) -> None: ...
 
-    def close_portal(self, name: bytes) -> "PGresult": ...
+    def close_portal(self, name: bytes) -> PGresult: ...
 
     def send_close_portal(self, name: bytes) -> None: ...
 
-    def get_result(self) -> "PGresult" | None: ...
+    def get_result(self) -> PGresult | None: ...
 
     def consume_input(self) -> None: ...
 
@@ -183,11 +183,11 @@ class PGconn(Protocol):
 
     def set_chunked_rows_mode(self, size: int) -> None: ...
 
-    def cancel_conn(self) -> "PGcancelConn": ...
+    def cancel_conn(self) -> PGcancelConn: ...
 
-    def get_cancel(self) -> "PGcancel": ...
+    def get_cancel(self) -> PGcancel: ...
 
-    def notifies(self) -> "PGnotify" | None: ...
+    def notifies(self) -> PGnotify | None: ...
 
     def put_copy_data(self, buffer: Buffer) -> int: ...
 
@@ -207,7 +207,7 @@ class PGconn(Protocol):
 
     def change_password(self, user: bytes, passwd: bytes) -> None: ...
 
-    def make_empty_result(self, exec_status: int) -> "PGresult": ...
+    def make_empty_result(self, exec_status: int) -> PGresult: ...
 
     @property
     def pipeline_status(self) -> int: ...
@@ -271,7 +271,7 @@ class PGresult(Protocol):
     @property
     def oid_value(self) -> int: ...
 
-    def set_attributes(self, descriptions: list["PGresAttDesc"]) -> None: ...
+    def set_attributes(self, descriptions: list[PGresAttDesc]) -> None: ...
 
 
 class PGcancelConn(Protocol):
@@ -303,13 +303,13 @@ class PGcancel(Protocol):
 
 class Conninfo(Protocol):
     @classmethod
-    def get_defaults(cls) -> list["ConninfoOption"]: ...
+    def get_defaults(cls) -> list[ConninfoOption]: ...
 
     @classmethod
-    def parse(cls, conninfo: bytes) -> list["ConninfoOption"]: ...
+    def parse(cls, conninfo: bytes) -> list[ConninfoOption]: ...
 
     @classmethod
-    def _options_from_array(cls, opts: Sequence[Any]) -> list["ConninfoOption"]: ...
+    def _options_from_array(cls, opts: Sequence[Any]) -> list[ConninfoOption]: ...
 
 
 class Escaping(Protocol):
index a4b5c6828f29e4f53b172d7ee5bdf2d5f6e52905..33c3d7e3adbfb1b1bb8a553d8f92a1fc189af3cd 100644 (file)
@@ -81,7 +81,7 @@ class PGconn:
 
     def __init__(self, pgconn_ptr: impl.PGconn_struct):
         self._pgconn_ptr: impl.PGconn_struct | None = pgconn_ptr
-        self.notice_handler: Callable[["abc.PGresult"], None] | None = None
+        self.notice_handler: Callable[[abc.PGresult], None] | None = None
         self.notify_handler: Callable[[PGnotify], None] | None = None
 
         # Keep alive for the lifetime of PGconn
@@ -102,7 +102,7 @@ class PGconn:
         return f"<{cls} {info} at 0x{id(self):x}>"
 
     @classmethod
-    def connect(cls, conninfo: bytes) -> "PGconn":
+    def connect(cls, conninfo: bytes) -> PGconn:
         if not isinstance(conninfo, bytes):
             raise TypeError(f"bytes expected, got {type(conninfo)} instead")
 
@@ -112,7 +112,7 @@ class PGconn:
         return cls(pgconn_ptr)
 
     @classmethod
-    def connect_start(cls, conninfo: bytes) -> "PGconn":
+    def connect_start(cls, conninfo: bytes) -> PGconn:
         if not isinstance(conninfo, bytes):
             raise TypeError(f"bytes expected, got {type(conninfo)} instead")
 
@@ -145,7 +145,7 @@ class PGconn:
         return addressof(self._pgconn_ptr.contents)  # type: ignore[attr-defined]
 
     @property
-    def info(self) -> list["ConninfoOption"]:
+    def info(self) -> list[ConninfoOption]:
         self._ensure_pgconn()
         opts = impl.PQconninfo(self._pgconn_ptr)
         if not opts:
@@ -261,7 +261,7 @@ class PGconn:
     def ssl_in_use(self) -> bool:
         return self._call_bool(impl.PQsslInUse)
 
-    def exec_(self, command: bytes) -> "PGresult":
+    def exec_(self, command: bytes) -> PGresult:
         if not isinstance(command, bytes):
             raise TypeError(f"bytes expected, got {type(command)} instead")
         self._ensure_pgconn()
@@ -280,11 +280,11 @@ class PGconn:
     def exec_params(
         self,
         command: bytes,
-        param_values: Sequence["abc.Buffer" | None] | None,
+        param_values: Sequence[abc.Buffer | None] | None,
         param_types: Sequence[int] | None = None,
         param_formats: Sequence[int] | None = None,
         result_format: int = Format.TEXT,
-    ) -> "PGresult":
+    ) -> PGresult:
         args = self._query_params_args(
             command, param_values, param_types, param_formats, result_format
         )
@@ -297,7 +297,7 @@ class PGconn:
     def send_query_params(
         self,
         command: bytes,
-        param_values: Sequence["abc.Buffer" | None] | None,
+        param_values: Sequence[abc.Buffer | None] | None,
         param_types: Sequence[int] | None = None,
         param_formats: Sequence[int] | None = None,
         result_format: int = Format.TEXT,
@@ -334,7 +334,7 @@ class PGconn:
     def send_query_prepared(
         self,
         name: bytes,
-        param_values: Sequence["abc.Buffer" | None] | None,
+        param_values: Sequence[abc.Buffer | None] | None,
         param_formats: Sequence[int] | None = None,
         result_format: int = Format.TEXT,
     ) -> None:
@@ -354,7 +354,7 @@ class PGconn:
     def _query_params_args(
         self,
         command: bytes,
-        param_values: Sequence["abc.Buffer" | None] | None,
+        param_values: Sequence[abc.Buffer | None] | None,
         param_types: Sequence[int] | None = None,
         param_formats: Sequence[int] | None = None,
         result_format: int = Format.TEXT,
@@ -415,7 +415,7 @@ class PGconn:
         name: bytes,
         command: bytes,
         param_types: Sequence[int] | None = None,
-    ) -> "PGresult":
+    ) -> PGresult:
         if not isinstance(name, bytes):
             raise TypeError(f"'name' must be bytes, got {type(name)} instead")
 
@@ -438,10 +438,10 @@ class PGconn:
     def exec_prepared(
         self,
         name: bytes,
-        param_values: Sequence["abc.Buffer"] | None,
+        param_values: Sequence[abc.Buffer] | None,
         param_formats: Sequence[int] | None = None,
         result_format: int = 0,
-    ) -> "PGresult":
+    ) -> PGresult:
         if not isinstance(name, bytes):
             raise TypeError(f"'name' must be bytes, got {type(name)} instead")
 
@@ -487,7 +487,7 @@ class PGconn:
             )
         return PGresult(rv)
 
-    def describe_prepared(self, name: bytes) -> "PGresult":
+    def describe_prepared(self, name: bytes) -> PGresult:
         if not isinstance(name, bytes):
             raise TypeError(f"'name' must be bytes, got {type(name)} instead")
         self._ensure_pgconn()
@@ -505,7 +505,7 @@ class PGconn:
                 f"sending describe prepared failed: {error_message(self)}"
             )
 
-    def describe_portal(self, name: bytes) -> "PGresult":
+    def describe_portal(self, name: bytes) -> PGresult:
         if not isinstance(name, bytes):
             raise TypeError(f"'name' must be bytes, got {type(name)} instead")
         self._ensure_pgconn()
@@ -523,7 +523,7 @@ class PGconn:
                 f"sending describe portal failed: {error_message(self)}"
             )
 
-    def close_prepared(self, name: bytes) -> "PGresult":
+    def close_prepared(self, name: bytes) -> PGresult:
         if not isinstance(name, bytes):
             raise TypeError(f"'name' must be bytes, got {type(name)} instead")
         self._ensure_pgconn()
@@ -541,7 +541,7 @@ class PGconn:
                 f"sending close prepared failed: {error_message(self)}"
             )
 
-    def close_portal(self, name: bytes) -> "PGresult":
+    def close_portal(self, name: bytes) -> PGresult:
         if not isinstance(name, bytes):
             raise TypeError(f"'name' must be bytes, got {type(name)} instead")
         self._ensure_pgconn()
@@ -559,7 +559,7 @@ class PGconn:
                 f"sending close portal failed: {error_message(self)}"
             )
 
-    def get_result(self) -> "PGresult" | None:
+    def get_result(self) -> PGresult | None:
         rv = impl.PQgetResult(self._pgconn_ptr)
         return PGresult(rv) if rv else None
 
@@ -598,7 +598,7 @@ class PGconn:
         if not impl.PQsetChunkedRowsMode(self._pgconn_ptr, size):
             raise e.OperationalError("setting chunked rows mode failed")
 
-    def cancel_conn(self) -> "PGcancelConn":
+    def cancel_conn(self) -> PGcancelConn:
         """
         Create a connection over which a cancel request can be sent.
 
@@ -609,7 +609,7 @@ class PGconn:
             raise e.OperationalError("couldn't create cancelConn object")
         return PGcancelConn(rv)
 
-    def get_cancel(self) -> "PGcancel":
+    def get_cancel(self) -> PGcancel:
         """
         Create an object with the information needed to cancel a command.
 
@@ -630,7 +630,7 @@ class PGconn:
         else:
             return None
 
-    def put_copy_data(self, buffer: "abc.Buffer") -> int:
+    def put_copy_data(self, buffer: abc.Buffer) -> int:
         if not isinstance(buffer, bytes):
             buffer = bytes(buffer)
         rv = impl.PQputCopyData(self._pgconn_ptr, buffer, len(buffer))
@@ -720,7 +720,7 @@ class PGconn:
                 f"failed to change password change command: {error_message(self)}"
             )
 
-    def make_empty_result(self, exec_status: int) -> "PGresult":
+    def make_empty_result(self, exec_status: int) -> PGresult:
         rv = impl.PQmakeEmptyPGresult(self._pgconn_ptr, exec_status)
         if not rv:
             raise MemoryError("couldn't allocate empty PGresult")
@@ -1106,7 +1106,7 @@ class Escaping:
     def __init__(self, conn: PGconn | None = None):
         self.conn = conn
 
-    def escape_literal(self, data: "abc.Buffer") -> bytes:
+    def escape_literal(self, data: abc.Buffer) -> bytes:
         if not self.conn:
             raise e.OperationalError("escape_literal failed: no connection provided")
 
@@ -1123,7 +1123,7 @@ class Escaping:
         impl.PQfreemem(out)
         return rv
 
-    def escape_identifier(self, data: "abc.Buffer") -> bytes:
+    def escape_identifier(self, data: abc.Buffer) -> bytes:
         if not self.conn:
             raise e.OperationalError("escape_identifier failed: no connection provided")
 
@@ -1140,7 +1140,7 @@ class Escaping:
         impl.PQfreemem(out)
         return rv
 
-    def escape_string(self, data: "abc.Buffer") -> bytes:
+    def escape_string(self, data: abc.Buffer) -> bytes:
         if not isinstance(data, bytes):
             data = bytes(data)
 
@@ -1171,7 +1171,7 @@ class Escaping:
 
         return out.value
 
-    def escape_bytea(self, data: "abc.Buffer") -> bytes:
+    def escape_bytea(self, data: abc.Buffer) -> bytes:
         len_out = c_size_t()
         # TODO: might be able to do without a copy but it's a mess.
         # the C library does it better anyway, so maybe not worth optimising
@@ -1201,7 +1201,7 @@ class Escaping:
         impl.PQfreemem(out)
         return rv
 
-    def unescape_bytea(self, data: "abc.Buffer") -> bytes:
+    def unescape_bytea(self, data: abc.Buffer) -> bytes:
         # not needed, but let's keep it symmetric with the escaping:
         # if a connection is passed in, it must be valid.
         if self.conn:
index 52211e23bab7253cdea3e3e6a52c97ace1c3bd08..00c6aa20c2ddbbfc8c241a82c05fe52fe50f39b0 100644 (file)
@@ -6,7 +6,7 @@ psycopg raw queries cursors
 
 from __future__ import annotations
 
-from typing import TYPE_CHECKING
+from typing import Any, TYPE_CHECKING
 
 from .abc import ConnectionType, Query, Params
 from .sql import Composable
@@ -18,9 +18,8 @@ from ._queries import PostgresQuery
 from ._cursor_base import BaseCursor
 
 if TYPE_CHECKING:
-    from typing import Any  # noqa: F401
-    from .connection import Connection  # noqa: F401
-    from .connection_async import AsyncConnection  # noqa: F401
+    from .connection import Connection
+    from .connection_async import AsyncConnection
 
 
 class PostgresRawQuery(PostgresQuery):
@@ -55,9 +54,9 @@ class RawCursorMixin(BaseCursor[ConnectionType, Row]):
     _query_cls = PostgresRawQuery
 
 
-class RawCursor(RawCursorMixin["Connection[Any]", Row], Cursor[Row]):
+class RawCursor(RawCursorMixin[Connection[Any], Row], Cursor[Row]):
     __module__ = "psycopg"
 
 
-class AsyncRawCursor(RawCursorMixin["AsyncConnection[Any]", Row], AsyncCursor[Row]):
+class AsyncRawCursor(RawCursorMixin[AsyncConnection[Any], Row], AsyncCursor[Row]):
     __module__ = "psycopg"
index 790e9c6243fa7f24829f88e4376c1c271ae16520..1a4bbd538546f45360fb2d4ef3f6e1f72695a83c 100644 (file)
@@ -62,7 +62,7 @@ class RowFactory(Protocol[Row]):
     use the values to create a dictionary for each record.
     """
 
-    def __call__(self, __cursor: "Cursor[Any]") -> RowMaker[Row]: ...
+    def __call__(self, __cursor: Cursor[Any]) -> RowMaker[Row]: ...
 
 
 class AsyncRowFactory(Protocol[Row]):
@@ -70,7 +70,7 @@ class AsyncRowFactory(Protocol[Row]):
     Like `RowFactory`, taking an async cursor as argument.
     """
 
-    def __call__(self, __cursor: "AsyncCursor[Any]") -> RowMaker[Row]: ...
+    def __call__(self, __cursor: AsyncCursor[Any]) -> RowMaker[Row]: ...
 
 
 class BaseRowFactory(Protocol[Row]):
@@ -78,7 +78,7 @@ class BaseRowFactory(Protocol[Row]):
     Like `RowFactory`, taking either type of cursor as argument.
     """
 
-    def __call__(self, __cursor: "BaseCursor[Any, Any]") -> RowMaker[Row]: ...
+    def __call__(self, __cursor: BaseCursor[Any, Any]) -> RowMaker[Row]: ...
 
 
 TupleRow: TypeAlias = tuple[Any, ...]
@@ -96,7 +96,7 @@ database.
 """
 
 
-def tuple_row(cursor: "BaseCursor[Any, Any]") -> "RowMaker[TupleRow]":
+def tuple_row(cursor: BaseCursor[Any, Any]) -> RowMaker[TupleRow]:
     r"""Row factory to represent rows as simple tuples.
 
     This is the default factory, used when `~psycopg.Connection.connect()` or
@@ -109,7 +109,7 @@ def tuple_row(cursor: "BaseCursor[Any, Any]") -> "RowMaker[TupleRow]":
     return tuple
 
 
-def dict_row(cursor: "BaseCursor[Any, Any]") -> "RowMaker[DictRow]":
+def dict_row(cursor: BaseCursor[Any, Any]) -> RowMaker[DictRow]:
     """Row factory to represent rows as dictionaries.
 
     The dictionary keys are taken from the column names of the returned columns.
@@ -124,9 +124,7 @@ def dict_row(cursor: "BaseCursor[Any, Any]") -> "RowMaker[DictRow]":
     return dict_row_
 
 
-def namedtuple_row(
-    cursor: "BaseCursor[Any, Any]",
-) -> "RowMaker[NamedTuple]":
+def namedtuple_row(cursor: BaseCursor[Any, Any]) -> RowMaker[NamedTuple]:
     """Row factory to represent rows as `~collections.namedtuple`.
 
     The field names are taken from the column names of the returned columns,
@@ -160,7 +158,7 @@ def class_row(cls: type[T]) -> BaseRowFactory[T]:
     :rtype: `!Callable[[Cursor],` `RowMaker`\[~T]]
     """
 
-    def class_row_(cursor: "BaseCursor[Any, Any]") -> "RowMaker[T]":
+    def class_row_(cursor: BaseCursor[Any, Any]) -> RowMaker[T]:
         names = _get_names(cursor)
         if names is None:
             return no_result
@@ -180,7 +178,7 @@ def args_row(func: Callable[..., T]) -> BaseRowFactory[T]:
         returned by the query as positional arguments.
     """
 
-    def args_row_(cur: "BaseCursor[Any, T]") -> "RowMaker[T]":
+    def args_row_(cur: BaseCursor[Any, T]) -> RowMaker[T]:
         def args_row__(values: Sequence[Any]) -> T:
             return func(*values)
 
@@ -196,7 +194,7 @@ def kwargs_row(func: Callable[..., T]) -> BaseRowFactory[T]:
         returned by the query as keyword arguments.
     """
 
-    def kwargs_row_(cursor: "BaseCursor[Any, T]") -> "RowMaker[T]":
+    def kwargs_row_(cursor: BaseCursor[Any, T]) -> RowMaker[T]:
         names = _get_names(cursor)
         if names is None:
             return no_result
@@ -209,7 +207,7 @@ def kwargs_row(func: Callable[..., T]) -> BaseRowFactory[T]:
     return kwargs_row_
 
 
-def scalar_row(cursor: "BaseCursor[Any, Any]") -> "RowMaker[Any]":
+def scalar_row(cursor: BaseCursor[Any, Any]) -> RowMaker[Any]:
     """
     Generate a row factory returning the first column
     as a scalar value.
@@ -241,7 +239,7 @@ def no_result(values: Sequence[Any]) -> NoReturn:
     raise e.InterfaceError("the cursor doesn't have a result")
 
 
-def _get_names(cursor: "BaseCursor[Any, Any]") -> list[str] | None:
+def _get_names(cursor: BaseCursor[Any, Any]) -> list[str] | None:
     res = cursor.pgresult
     if not res:
         return None
@@ -256,7 +254,7 @@ def _get_names(cursor: "BaseCursor[Any, Any]") -> list[str] | None:
     ]
 
 
-def _get_nfields(res: "PGresult") -> int | None:
+def _get_nfields(res: PGresult) -> int | None:
     """
     Return the number of columns in a result, if it returns tuples else None
 
index 2f34d3eacda843a32a99833c05094fdcc4c141a5..a75281bfba6abb3cc3c11f574cc15bf06af74ac5 100644 (file)
@@ -211,14 +211,14 @@ class ServerCursorMixin(BaseCursor[ConnectionType, Row]):
         return sql.SQL(" ").join(parts)
 
 
-class ServerCursor(ServerCursorMixin["Connection[Any]", Row], Cursor[Row]):
+class ServerCursor(ServerCursorMixin[Connection[Any], Row], Cursor[Row]):
     __module__ = "psycopg"
     __slots__ = ()
 
     @overload
     def __init__(
         self,
-        connection: "Connection[Row]",
+        connection: Connection[Row],
         name: str,
         *,
         scrollable: bool | None = None,
@@ -228,7 +228,7 @@ class ServerCursor(ServerCursorMixin["Connection[Any]", Row], Cursor[Row]):
     @overload
     def __init__(
         self,
-        connection: "Connection[Any]",
+        connection: Connection[Any],
         name: str,
         *,
         row_factory: RowFactory[Row],
@@ -238,7 +238,7 @@ class ServerCursor(ServerCursorMixin["Connection[Any]", Row], Cursor[Row]):
 
     def __init__(
         self,
-        connection: "Connection[Any]",
+        connection: Connection[Any],
         name: str,
         *,
         row_factory: RowFactory[Row] | None = None,
@@ -348,16 +348,14 @@ class ServerCursor(ServerCursorMixin["Connection[Any]", Row], Cursor[Row]):
             self._pos = value
 
 
-class AsyncServerCursor(
-    ServerCursorMixin["AsyncConnection[Any]", Row], AsyncCursor[Row]
-):
+class AsyncServerCursor(ServerCursorMixin[AsyncConnection[Any], Row], AsyncCursor[Row]):
     __module__ = "psycopg"
     __slots__ = ()
 
     @overload
     def __init__(
         self,
-        connection: "AsyncConnection[Row]",
+        connection: AsyncConnection[Row],
         name: str,
         *,
         scrollable: bool | None = None,
@@ -367,7 +365,7 @@ class AsyncServerCursor(
     @overload
     def __init__(
         self,
-        connection: "AsyncConnection[Any]",
+        connection: AsyncConnection[Any],
         name: str,
         *,
         row_factory: AsyncRowFactory[Row],
@@ -377,7 +375,7 @@ class AsyncServerCursor(
 
     def __init__(
         self,
-        connection: "AsyncConnection[Any]",
+        connection: AsyncConnection[Any],
         name: str,
         *,
         row_factory: AsyncRowFactory[Row] | None = None,
index f44fc5ac50571e6190c26cee072cde030bfdd882..2d352445df407466af0802a5d306defca908b83a 100644 (file)
@@ -9,7 +9,7 @@ from __future__ import annotations
 import logging
 
 from types import TracebackType
-from typing import Generic, Iterator, TYPE_CHECKING
+from typing import Any, Generic, Iterator, TYPE_CHECKING
 
 from . import pq
 from . import sql
@@ -19,7 +19,6 @@ from ._compat import Self
 from .pq.misc import connection_summary
 
 if TYPE_CHECKING:
-    from typing import Any
     from .connection import Connection
     from .connection_async import AsyncConnection
 
@@ -228,7 +227,7 @@ class BaseTransaction(Generic[ConnectionType]):
         )
 
 
-class Transaction(BaseTransaction["Connection[Any]"]):
+class Transaction(BaseTransaction[Connection[Any]]):
     """
     Returned by `Connection.transaction()` to handle a transaction block.
     """
@@ -236,7 +235,7 @@ class Transaction(BaseTransaction["Connection[Any]"]):
     __module__ = "psycopg"
 
     @property
-    def connection(self) -> "Connection[Any]":
+    def connection(self) -> Connection[Any]:
         """The connection the object is managing."""
         return self._conn
 
@@ -258,7 +257,7 @@ class Transaction(BaseTransaction["Connection[Any]"]):
             return False
 
 
-class AsyncTransaction(BaseTransaction["AsyncConnection[Any]"]):
+class AsyncTransaction(BaseTransaction[AsyncConnection[Any]]):
     """
     Returned by `AsyncConnection.transaction()` to handle a transaction block.
     """
@@ -266,7 +265,7 @@ class AsyncTransaction(BaseTransaction["AsyncConnection[Any]"]):
     __module__ = "psycopg"
 
     @property
-    def connection(self) -> "AsyncConnection[Any]":
+    def connection(self) -> AsyncConnection[Any]:
         return self._conn
 
     async def __aenter__(self) -> Self:
index 91cb0e40097751e1642a2dab92468a525d1986ec..4a770d125800f0889d82d56abc8c22aa3803c999 100644 (file)
@@ -53,7 +53,7 @@ class CompositeInfo(TypeInfo):
         self.python_type: type | None = None
 
     @classmethod
-    def _get_info_query(cls, conn: "BaseConnection[Any]") -> abc.Query:
+    def _get_info_query(cls, conn: BaseConnection[Any]) -> abc.Query:
         return sql.SQL(
             """\
 SELECT
index 08bdf6d8164b9f91919f3415ce497313918ab79d..b701a020571e2d0c4ac61591ad335e859c434ee7 100644 (file)
@@ -678,7 +678,7 @@ class IntervalBinaryLoader(Loader):
             raise DataError(f"can't parse interval: {e}") from None
 
 
-def _get_datestyle(conn: "BaseConnection[Any]" | None) -> bytes:
+def _get_datestyle(conn: BaseConnection[Any] | None) -> bytes:
     if conn:
         ds = conn.pgconn.parameter_status(b"DateStyle")
         if ds:
@@ -687,7 +687,7 @@ def _get_datestyle(conn: "BaseConnection[Any]" | None) -> bytes:
     return b"ISO, DMY"
 
 
-def _get_intervalstyle(conn: "BaseConnection[Any]" | None) -> bytes:
+def _get_intervalstyle(conn: BaseConnection[Any] | None) -> bytes:
     if conn:
         ints = conn.pgconn.parameter_status(b"IntervalStyle")
         if ints:
@@ -697,7 +697,7 @@ def _get_intervalstyle(conn: "BaseConnection[Any]" | None) -> bytes:
 
 
 def _get_timestamp_load_error(
-    conn: "BaseConnection[Any]" | None, data: Buffer, ex: Exception | None = None
+    conn: BaseConnection[Any] | None, data: Buffer, ex: Exception | None = None
 ) -> Exception:
     s = bytes(data).decode("utf8", "replace")
 
index 3f1f44ac91e668e1e6fa518e233a21f26cacc93b..65a75d1bd0b40db58c3071f242d9ecf53d705888 100644 (file)
@@ -50,7 +50,7 @@ class EnumInfo(TypeInfo):
         self.enum: type[Enum] | None = None
 
     @classmethod
-    def _get_info_query(cls, conn: "BaseConnection[Any]") -> Query:
+    def _get_info_query(cls, conn: BaseConnection[Any]) -> Query:
         return sql.SQL(
             """\
 SELECT name, oid, array_oid, array_agg(label) AS labels
index b5dbdfffb3369c2c417a2a1f272bee7c5f7f965e..d8070279f1f1afd6c9ddeb0b3bca55efd3c3722f 100644 (file)
@@ -47,7 +47,7 @@ class MultirangeInfo(TypeInfo):
         self.subtype_oid = subtype_oid
 
     @classmethod
-    def _get_info_query(cls, conn: "BaseConnection[Any]") -> Query:
+    def _get_info_query(cls, conn: BaseConnection[Any]) -> Query:
         if conn.info.server_version < 140000:
             raise e.NotSupportedError(
                 "multirange types are only available from PostgreSQL 14"
index 0fa3926fec5c0cfea92e21acf7c08fb33e0860b1..bdce29401a2ea8f160c6d244c1d0eef775a34380 100644 (file)
@@ -53,7 +53,7 @@ class RangeInfo(TypeInfo):
         self.subtype_oid = subtype_oid
 
     @classmethod
-    def _get_info_query(cls, conn: "BaseConnection[Any]") -> Query:
+    def _get_info_query(cls, conn: BaseConnection[Any]) -> Query:
         return sql.SQL(
             """\
 SELECT t.typname AS name, t.oid AS oid, t.typarray AS array_oid,
index cb3b24e12035f84277f958b7e155c2f3ebc90341..b802a6c8370a61565a251f3ce569dc635810348d 100644 (file)
@@ -174,7 +174,7 @@ class BytesBinaryDumper(Dumper):
 
 
 class ByteaLoader(Loader):
-    _escaping: "EscapingProto"
+    _escaping: EscapingProto
 
     def __init__(self, oid: int, context: AdaptContext | None = None):
         super().__init__(oid, context)
index fb9485d8e6e790470930b99478b1d51126b5e931..33d8acd750ec85d1ec9e54efd26e6de56dab0b7e 100644 (file)
@@ -17,20 +17,20 @@ if TYPE_CHECKING:
     import uuid
 
 # Importing the uuid module is slow, so import it only on request.
-UUID: Callable[..., "uuid.UUID"] = None  # type: ignore[assignment]
+UUID: Callable[..., uuid.UUID] = None  # type: ignore[assignment]
 
 
 class UUIDDumper(Dumper):
     oid = _oids.UUID_OID
 
-    def dump(self, obj: "uuid.UUID") -> Buffer | None:
+    def dump(self, obj: uuid.UUID) -> Buffer | None:
         return obj.hex.encode()
 
 
 class UUIDBinaryDumper(UUIDDumper):
     format = Format.BINARY
 
-    def dump(self, obj: "uuid.UUID") -> Buffer | None:
+    def dump(self, obj: uuid.UUID) -> Buffer | None:
         return obj.bytes
 
 
@@ -41,7 +41,7 @@ class UUIDLoader(Loader):
         if UUID is None:
             from uuid import UUID
 
-    def load(self, data: Buffer) -> "uuid.UUID":
+    def load(self, data: Buffer) -> uuid.UUID:
         if isinstance(data, memoryview):
             data = bytes(data)
         return UUID(data.decode())
@@ -50,7 +50,7 @@ class UUIDLoader(Loader):
 class UUIDBinaryLoader(UUIDLoader):
     format = Format.BINARY
 
-    def load(self, data: Buffer) -> "uuid.UUID":
+    def load(self, data: Buffer) -> uuid.UUID:
         if isinstance(data, memoryview):
             data = bytes(data)
         return UUID(bytes=data)
index d0114852867136019599f30c38e8ee7dc1c7e6a4..c64929583ad93a5ede11d2280d961e098acb7f89 100644 (file)
@@ -94,7 +94,7 @@ cdef class PGconn:
             return None
 
     @property
-    def info(self) -> list["ConninfoOption"]:
+    def info(self) -> list[ConninfoOption]:
         _ensure_pgconn(self)
         cdef libpq.PQconninfoOption *opts = libpq.PQconninfo(self._pgconn_ptr)
         if opts is NULL:
index 5f04d316efc5867fb50beda8274ba2c9a79ebe5a..d3ffccf3d6f846ccdbb8bbe4c81b2f7fc351c92b 100644 (file)
@@ -25,8 +25,8 @@ ConnectionCB: TypeAlias = Callable[[CT], None]
 AsyncConnectionCB: TypeAlias = Callable[[ACT], Awaitable[None]]
 
 # Callbacks to pass the pool to on connection failure
-ConnectFailedCB: TypeAlias = Callable[["ConnectionPool[Any]"], None]
+ConnectFailedCB: TypeAlias = Callable[[ConnectionPool[Any]], None]
 AsyncConnectFailedCB: TypeAlias = (
-    Callable[["AsyncConnectionPool[Any]"], None]
-    | Callable[["AsyncConnectionPool[Any]"], Awaitable[None]]
+    Callable[[AsyncConnectionPool[Any]], None]
+    | Callable[[AsyncConnectionPool[Any]], Awaitable[None]]
 )
index 2937698c13791a10008579181b2ade163370af04..f0369681597c0b590bca3a69a98e35ce1f88ffd7 100644 (file)
@@ -144,7 +144,7 @@ class BasePool:
             else:
                 raise PoolClosed(f"the pool {self.name!r} is not open yet")
 
-    def _check_pool_putconn(self, conn: "BaseConnection[Any]") -> None:
+    def _check_pool_putconn(self, conn: BaseConnection[Any]) -> None:
         pool = getattr(conn, "_pool", None)
         if pool is self:
             return
@@ -194,7 +194,7 @@ class BasePool:
         """
         return value * (1.0 + ((max_pc - min_pc) * random()) + min_pc)
 
-    def _set_connection_expiry_date(self, conn: "BaseConnection[Any]") -> None:
+    def _set_connection_expiry_date(self, conn: BaseConnection[Any]) -> None:
         """Set an expiry date on a connection.
 
         Add some randomness to avoid mass reconnection.