From: Daniele Varrazzo Date: Thu, 30 May 2024 02:14:17 +0000 (+0200) Subject: refactor: avoid using types as strings where possible X-Git-Tag: 3.2.0~19^2~1 X-Git-Url: http://git.ipfire.org/gitweb/gitweb.cgi?a=commitdiff_plain;h=42151a3bd87e7ea6cc3e91e75af34429eaabff95;p=thirdparty%2Fpsycopg.git refactor: avoid using types as strings where possible --- diff --git a/psycopg/psycopg/_adapters_map.py b/psycopg/psycopg/_adapters_map.py index 55a3cf1e4..53e1b583b 100644 --- a/psycopg/psycopg/_adapters_map.py +++ b/psycopg/psycopg/_adapters_map.py @@ -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: diff --git a/psycopg/psycopg/_column.py b/psycopg/psycopg/_column.py index 2e441b678..92973824e 100644 --- a/psycopg/psycopg/_column.py +++ b/psycopg/psycopg/_column.py @@ -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 diff --git a/psycopg/psycopg/_connection_base.py b/psycopg/psycopg/_connection_base.py index 691969b81..8b0277dad 100644 --- a/psycopg/psycopg/_connection_base.py +++ b/psycopg/psycopg/_connection_base.py @@ -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. diff --git a/psycopg/psycopg/_copy.py b/psycopg/psycopg/_copy.py index 1c393a9d6..092d9635a 100644 --- a/psycopg/psycopg/_copy.py +++ b/psycopg/psycopg/_copy.py @@ -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. diff --git a/psycopg/psycopg/_copy_async.py b/psycopg/psycopg/_copy_async.py index 2c630da9b..6cddac413 100644 --- a/psycopg/psycopg/_copy_async.py +++ b/psycopg/psycopg/_copy_async.py @@ -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. diff --git a/psycopg/psycopg/_copy_base.py b/psycopg/psycopg/_copy_base.py index 354b589e4..d3a143c5f 100644 --- a/psycopg/psycopg/_copy_base.py +++ b/psycopg/psycopg/_copy_base.py @@ -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, ): diff --git a/psycopg/psycopg/_cursor_base.py b/psycopg/psycopg/_cursor_base.py index 6fb08dcfa..1f2234513 100644 --- a/psycopg/psycopg/_cursor_base.py +++ b/psycopg/psycopg/_cursor_base.py @@ -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. """ diff --git a/psycopg/psycopg/_encodings.py b/psycopg/psycopg/_encodings.py index a6c0ac4c4..b515f96fd 100644 --- a/psycopg/psycopg/_encodings.py +++ b/psycopg/psycopg/_encodings.py @@ -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. diff --git a/psycopg/psycopg/_pipeline.py b/psycopg/psycopg/_pipeline.py index 239b619b5..9b6457218 100644 --- a/psycopg/psycopg/_pipeline.py +++ b/psycopg/psycopg/_pipeline.py @@ -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: diff --git a/psycopg/psycopg/_preparing.py b/psycopg/psycopg/_preparing.py index eccf260de..4face7687 100644 --- a/psycopg/psycopg/_preparing.py +++ b/psycopg/psycopg/_preparing.py @@ -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 diff --git a/psycopg/psycopg/_py_transformer.py b/psycopg/psycopg/_py_transformer.py index 3a1c2e5ab..c2f4ea21c 100644 --- a/psycopg/psycopg/_py_transformer.py +++ b/psycopg/psycopg/_py_transformer.py @@ -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, diff --git a/psycopg/psycopg/_queries.py b/psycopg/psycopg/_queries.py index 517ed7af9..0cd615b6a 100644 --- a/psycopg/psycopg/_queries.py +++ b/psycopg/psycopg/_queries.py @@ -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 diff --git a/psycopg/psycopg/abc.py b/psycopg/psycopg/abc.py index 6eef15081..e5e02d7e6 100644 --- a/psycopg/psycopg/abc.py +++ b/psycopg/psycopg/abc.py @@ -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, ...]: ... diff --git a/psycopg/psycopg/adapt.py b/psycopg/psycopg/adapt.py index fa590332c..889801de9 100644 --- a/psycopg/psycopg/adapt.py +++ b/psycopg/psycopg/adapt.py @@ -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 diff --git a/psycopg/psycopg/client_cursor.py b/psycopg/psycopg/client_cursor.py index 5a64e5fe7..058d0fe62 100644 --- a/psycopg/psycopg/client_cursor.py +++ b/psycopg/psycopg/client_cursor.py @@ -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" diff --git a/psycopg/psycopg/connection.py b/psycopg/psycopg/connection.py index c285add9e..277d3ab7c 100644 --- a/psycopg/psycopg/connection.py +++ b/psycopg/psycopg/connection.py @@ -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) diff --git a/psycopg/psycopg/connection_async.py b/psycopg/psycopg/connection_async.py index 12de50a54..d66f6fbf3 100644 --- a/psycopg/psycopg/connection_async.py +++ b/psycopg/psycopg/connection_async.py @@ -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) diff --git a/psycopg/psycopg/crdb/connection.py b/psycopg/psycopg/crdb/connection.py index 5792e6f6b..74b34a7db 100644 --- a/psycopg/psycopg/crdb/connection.py +++ b/psycopg/psycopg/crdb/connection.py @@ -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. """ diff --git a/psycopg/psycopg/cursor.py b/psycopg/psycopg/cursor.py index 6d1ddf019..fdcd7e66e 100644 --- a/psycopg/psycopg/cursor.py +++ b/psycopg/psycopg/cursor.py @@ -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__ = () diff --git a/psycopg/psycopg/cursor_async.py b/psycopg/psycopg/cursor_async.py index b708d5d6c..c07fccc7f 100644 --- a/psycopg/psycopg/cursor_async.py +++ b/psycopg/psycopg/cursor_async.py @@ -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__ = () diff --git a/psycopg/psycopg/errors.py b/psycopg/psycopg/errors.py index 5d6472bba..f6b1410c4 100644 --- a/psycopg/psycopg/errors.py +++ b/psycopg/psycopg/errors.py @@ -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: diff --git a/psycopg/psycopg/pq/_debug.py b/psycopg/psycopg/pq/_debug.py index bc888648a..9d1d36389 100644 --- a/psycopg/psycopg/pq/_debug.py +++ b/psycopg/psycopg/pq/_debug.py @@ -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: diff --git a/psycopg/psycopg/pq/abc.py b/psycopg/psycopg/pq/abc.py index 876a3f408..4bf350934 100644 --- a/psycopg/psycopg/pq/abc.py +++ b/psycopg/psycopg/pq/abc.py @@ -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): diff --git a/psycopg/psycopg/pq/pq_ctypes.py b/psycopg/psycopg/pq/pq_ctypes.py index a4b5c6828..33c3d7e3a 100644 --- a/psycopg/psycopg/pq/pq_ctypes.py +++ b/psycopg/psycopg/pq/pq_ctypes.py @@ -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: diff --git a/psycopg/psycopg/raw_cursor.py b/psycopg/psycopg/raw_cursor.py index 52211e23b..00c6aa20c 100644 --- a/psycopg/psycopg/raw_cursor.py +++ b/psycopg/psycopg/raw_cursor.py @@ -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" diff --git a/psycopg/psycopg/rows.py b/psycopg/psycopg/rows.py index 790e9c624..1a4bbd538 100644 --- a/psycopg/psycopg/rows.py +++ b/psycopg/psycopg/rows.py @@ -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 diff --git a/psycopg/psycopg/server_cursor.py b/psycopg/psycopg/server_cursor.py index 2f34d3eac..a75281bfb 100644 --- a/psycopg/psycopg/server_cursor.py +++ b/psycopg/psycopg/server_cursor.py @@ -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, diff --git a/psycopg/psycopg/transaction.py b/psycopg/psycopg/transaction.py index f44fc5ac5..2d352445d 100644 --- a/psycopg/psycopg/transaction.py +++ b/psycopg/psycopg/transaction.py @@ -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: diff --git a/psycopg/psycopg/types/composite.py b/psycopg/psycopg/types/composite.py index 91cb0e400..4a770d125 100644 --- a/psycopg/psycopg/types/composite.py +++ b/psycopg/psycopg/types/composite.py @@ -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 diff --git a/psycopg/psycopg/types/datetime.py b/psycopg/psycopg/types/datetime.py index 08bdf6d81..b701a0205 100644 --- a/psycopg/psycopg/types/datetime.py +++ b/psycopg/psycopg/types/datetime.py @@ -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") diff --git a/psycopg/psycopg/types/enum.py b/psycopg/psycopg/types/enum.py index 3f1f44ac9..65a75d1bd 100644 --- a/psycopg/psycopg/types/enum.py +++ b/psycopg/psycopg/types/enum.py @@ -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 diff --git a/psycopg/psycopg/types/multirange.py b/psycopg/psycopg/types/multirange.py index b5dbdfffb..d8070279f 100644 --- a/psycopg/psycopg/types/multirange.py +++ b/psycopg/psycopg/types/multirange.py @@ -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" diff --git a/psycopg/psycopg/types/range.py b/psycopg/psycopg/types/range.py index 0fa3926fe..bdce29401 100644 --- a/psycopg/psycopg/types/range.py +++ b/psycopg/psycopg/types/range.py @@ -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, diff --git a/psycopg/psycopg/types/string.py b/psycopg/psycopg/types/string.py index cb3b24e12..b802a6c83 100644 --- a/psycopg/psycopg/types/string.py +++ b/psycopg/psycopg/types/string.py @@ -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) diff --git a/psycopg/psycopg/types/uuid.py b/psycopg/psycopg/types/uuid.py index fb9485d8e..33d8acd75 100644 --- a/psycopg/psycopg/types/uuid.py +++ b/psycopg/psycopg/types/uuid.py @@ -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) diff --git a/psycopg_c/psycopg_c/pq/pgconn.pyx b/psycopg_c/psycopg_c/pq/pgconn.pyx index d01148528..c64929583 100644 --- a/psycopg_c/psycopg_c/pq/pgconn.pyx +++ b/psycopg_c/psycopg_c/pq/pgconn.pyx @@ -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: diff --git a/psycopg_pool/psycopg_pool/abc.py b/psycopg_pool/psycopg_pool/abc.py index 5f04d316e..d3ffccf3d 100644 --- a/psycopg_pool/psycopg_pool/abc.py +++ b/psycopg_pool/psycopg_pool/abc.py @@ -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]] ) diff --git a/psycopg_pool/psycopg_pool/base.py b/psycopg_pool/psycopg_pool/base.py index 2937698c1..f03696815 100644 --- a/psycopg_pool/psycopg_pool/base.py +++ b/psycopg_pool/psycopg_pool/base.py @@ -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.