From: Daniele Varrazzo Date: Thu, 30 May 2024 03:28:59 +0000 (+0200) Subject: fix: fix type annotation for Python 3.8 X-Git-Tag: 3.2.0~19^2 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=4e90e28eddbb62e9c0898894e3c731e829eacd2c;p=thirdparty%2Fpsycopg.git fix: fix type annotation for Python 3.8 --- diff --git a/psycopg/psycopg/_adapters_map.py b/psycopg/psycopg/_adapters_map.py index 53e1b583b..c633b6bef 100644 --- a/psycopg/psycopg/_adapters_map.py +++ b/psycopg/psycopg/_adapters_map.py @@ -282,7 +282,7 @@ class AdaptersMap: from psycopg import types if cls.__module__.startswith(types.__name__): - new = cast(type[RV], getattr(_psycopg, cls.__name__, None)) + new = cast("type[RV]", getattr(_psycopg, cls.__name__, None)) if new: self._optimised[cls] = new return new diff --git a/psycopg/psycopg/_copy.py b/psycopg/psycopg/_copy.py index 092d9635a..1c393a9d6 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 + from .connection import Connection # noqa: F401 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 6cddac413..2c630da9b 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 + from .connection_async import AsyncConnection # noqa: F401 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/_pipeline.py b/psycopg/psycopg/_pipeline.py index 9b6457218..441b2147c 100644 --- a/psycopg/psycopg/_pipeline.py +++ b/psycopg/psycopg/_pipeline.py @@ -16,20 +16,20 @@ from .abc import PipelineCommand, PQGen from ._compat import Deque, Self, TypeAlias from .pq.misc import connection_summary from ._encodings import pgconn_encoding -from ._preparing import Key, Prepare from .generators import pipeline_communicate, fetch_many, send from ._capabilities import capabilities if TYPE_CHECKING: from .pq.abc import PGresult - from ._cursor_base import BaseCursor from .connection import Connection + from ._preparing import Key, Prepare # noqa: F401 + from ._cursor_base import BaseCursor # noqa: F401 from ._connection_base import BaseConnection from .connection_async import AsyncConnection PendingResult: TypeAlias = ( - tuple[BaseCursor[Any, Any], tuple[Key, Prepare, bytes] | None] | None + "tuple[BaseCursor[Any, Any], tuple[Key, Prepare, bytes] | None] | None" ) FATAL_ERROR = pq.ExecStatus.FATAL_ERROR diff --git a/psycopg/psycopg/_preparing.py b/psycopg/psycopg/_preparing.py index 4face7687..c48c86c09 100644 --- a/psycopg/psycopg/_preparing.py +++ b/psycopg/psycopg/_preparing.py @@ -19,7 +19,7 @@ if TYPE_CHECKING: from .pq.abc import PGresult from ._connection_base import BaseConnection -Key: TypeAlias = tuple[bytes, tuple[int, ...]] +Key: TypeAlias = "tuple[bytes, tuple[int, ...]]" COMMAND_OK = pq.ExecStatus.COMMAND_OK TUPLES_OK = pq.ExecStatus.TUPLES_OK @@ -48,7 +48,7 @@ class PrepareManager: # Counter to generate prepared statements names self._prepared_idx = 0 - self._to_flush = Deque[bytes | None]() + self._to_flush = Deque["bytes | None"]() @staticmethod def key(query: PostgresQuery) -> Key: diff --git a/psycopg/psycopg/_py_transformer.py b/psycopg/psycopg/_py_transformer.py index c2f4ea21c..0620113ee 100644 --- a/psycopg/psycopg/_py_transformer.py +++ b/psycopg/psycopg/_py_transformer.py @@ -17,20 +17,21 @@ from collections import defaultdict from . import pq from . import abc from . import errors as e -from .abc import Buffer, LoadFunc, AdaptContext, PyFormat, DumperKey, NoneType +from .abc import Buffer, LoadFunc, AdaptContext, PyFormat, NoneType from .rows import Row, RowMaker from ._oids import INVALID_OID, TEXT_OID from ._compat import TypeAlias from ._encodings import conn_encoding if TYPE_CHECKING: + from .abc import DumperKey # noqa: F401 from .adapt import AdaptersMap from .pq.abc import PGresult from ._connection_base import BaseConnection -DumperCache: TypeAlias = dict[DumperKey, abc.Dumper] -OidDumperCache: TypeAlias = dict[int, abc.Dumper] -LoaderCache: TypeAlias = dict[int, abc.Loader] +DumperCache: TypeAlias = "dict[DumperKey, abc.Dumper]" +OidDumperCache: TypeAlias = "dict[int, abc.Dumper]" +LoaderCache: TypeAlias = "dict[int, abc.Loader]" TEXT = pq.Format.TEXT PY_TEXT = PyFormat.TEXT diff --git a/psycopg/psycopg/_queries.py b/psycopg/psycopg/_queries.py index 0cd615b6a..537a65669 100644 --- a/psycopg/psycopg/_queries.py +++ b/psycopg/psycopg/_queries.py @@ -169,7 +169,7 @@ class PostgresQuery: # The type of the _query2pg() and _query2pg_nocache() methods _Query2Pg: TypeAlias = Callable[ - [bytes, str], tuple[bytes, list[PyFormat], list[str] | None, list[QueryPart]] + [bytes, str], "tuple[bytes, list[PyFormat], list[str] | None, list[QueryPart]]" ] @@ -285,7 +285,7 @@ class PostgresClientQuery(PostgresQuery): _Query2PgClient: TypeAlias = Callable[ - [bytes, str], tuple[bytes, list[str] | None, list[QueryPart]] + [bytes, str], "tuple[bytes, list[str] | None, list[QueryPart]]" ] diff --git a/psycopg/psycopg/_struct.py b/psycopg/psycopg/_struct.py index a09f8b535..01978a500 100644 --- a/psycopg/psycopg/_struct.py +++ b/psycopg/psycopg/_struct.py @@ -14,9 +14,9 @@ from .abc import Buffer from ._compat import TypeAlias PackInt: TypeAlias = Callable[[int], bytes] -UnpackInt: TypeAlias = Callable[[Buffer], tuple[int]] +UnpackInt: TypeAlias = Callable[[Buffer], "tuple[int]"] PackFloat: TypeAlias = Callable[[float], bytes] -UnpackFloat: TypeAlias = Callable[[Buffer], tuple[float]] +UnpackFloat: TypeAlias = Callable[[Buffer], "tuple[float]"] class UnpackLen(Protocol): diff --git a/psycopg/psycopg/abc.py b/psycopg/psycopg/abc.py index e5e02d7e6..edac47c2a 100644 --- a/psycopg/psycopg/abc.py +++ b/psycopg/psycopg/abc.py @@ -11,28 +11,29 @@ from typing import Protocol, Sequence, TYPE_CHECKING from . import pq from ._enums import PyFormat as PyFormat -from ._compat import LiteralString, TypeAlias, TypeVar +from ._compat import TypeAlias, TypeVar if TYPE_CHECKING: - from . import sql + from . import sql # noqa: F401 from .rows import Row, RowMaker from .pq.abc import PGresult - from .waiting import Wait, Ready + from .waiting import Wait, Ready # noqa: F401 + from ._compat import LiteralString # noqa: F401 from ._adapters_map import AdaptersMap from ._connection_base import BaseConnection NoneType: type = type(None) # An object implementing the buffer protocol -Buffer: TypeAlias = bytes | bytearray | memoryview +Buffer: TypeAlias = "bytes | bytearray | memoryview" -Query: TypeAlias = LiteralString | bytes | sql.SQL | sql.Composed -Params: TypeAlias = Sequence[Any] | Mapping[str, Any] +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] -DumperKey: TypeAlias = type | tuple["DumperKey", ...] -ConnParam: TypeAlias = str | int | None -ConnDict: TypeAlias = dict[str, ConnParam] +DumperKey: TypeAlias = "type | tuple[DumperKey, ...]" +ConnParam: TypeAlias = "str | int | None" +ConnDict: TypeAlias = "dict[str, ConnParam]" ConnMapping: TypeAlias = Mapping[str, ConnParam] @@ -40,13 +41,13 @@ ConnMapping: TypeAlias = Mapping[str, ConnParam] RV = TypeVar("RV") -PQGenConn: TypeAlias = Generator[tuple[int, Wait], Ready | int, RV] +PQGenConn: TypeAlias = Generator["tuple[int, Wait]", "Ready | int", RV] """Generator for processes where the connection file number can change. 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. """ @@ -63,7 +64,7 @@ class WaitFunc(Protocol): # Adaptation types -DumpFunc: TypeAlias = Callable[[Any], Buffer | None] +DumpFunc: TypeAlias = Callable[[Any], "Buffer | None"] LoadFunc: TypeAlias = Callable[[Buffer], Any] diff --git a/psycopg/psycopg/client_cursor.py b/psycopg/psycopg/client_cursor.py index 058d0fe62..5a64e5fe7 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 Any, TYPE_CHECKING +from typing import TYPE_CHECKING from functools import partial from ._queries import PostgresQuery, PostgresClientQuery @@ -22,8 +22,9 @@ from ._cursor_base import BaseCursor from .cursor_async import AsyncCursor if TYPE_CHECKING: - from .connection import Connection - from .connection_async import AsyncConnection + from typing import Any # noqa: F401 + from .connection import Connection # noqa: F401 + from .connection_async import AsyncConnection # noqa: F401 TEXT = pq.Format.TEXT BINARY = pq.Format.BINARY @@ -82,9 +83,11 @@ 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/cursor.py b/psycopg/psycopg/cursor.py index fdcd7e66e..6d1ddf019 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 c07fccc7f..b708d5d6c 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 f6b1410c4..0d162feaa 100644 --- a/psycopg/psycopg/errors.py +++ b/psycopg/psycopg/errors.py @@ -31,7 +31,7 @@ from ._compat import TypeAlias, TypeGuard if TYPE_CHECKING: from .pq.misc import PGnotify, ConninfoOption -ErrorInfo: TypeAlias = None | PGresult | dict[int, bytes | None] +ErrorInfo: TypeAlias = "PGresult | dict[int, bytes | None] | None" _sqlcodes: dict[str, type[Error]] = {} diff --git a/psycopg/psycopg/pq/_debug.py b/psycopg/psycopg/pq/_debug.py index 9d1d36389..70855c55d 100644 --- a/psycopg/psycopg/pq/_debug.py +++ b/psycopg/psycopg/pq/_debug.py @@ -30,16 +30,14 @@ Suggested usage:: import inspect import logging -from typing import Any, Callable, TYPE_CHECKING +from typing import Any, Callable from functools import wraps from .._compat import Self, TypeVar +from . import abc from . import PGconn from .misc import connection_summary -if TYPE_CHECKING: - from . import abc - Func = TypeVar("Func", bound=Callable[..., Any]) logger = logging.getLogger("psycopg.debug") diff --git a/psycopg/psycopg/pq/abc.py b/psycopg/psycopg/pq/abc.py index 4bf350934..cd3fdbf5d 100644 --- a/psycopg/psycopg/pq/abc.py +++ b/psycopg/psycopg/pq/abc.py @@ -15,7 +15,7 @@ if TYPE_CHECKING: from .misc import PGnotify, ConninfoOption, PGresAttDesc # An object implementing the buffer protocol (ish) -Buffer: TypeAlias = bytes | bytearray | memoryview +Buffer: TypeAlias = "bytes | bytearray | memoryview" class PGconn(Protocol): diff --git a/psycopg/psycopg/raw_cursor.py b/psycopg/psycopg/raw_cursor.py index 00c6aa20c..03c1903c0 100644 --- a/psycopg/psycopg/raw_cursor.py +++ b/psycopg/psycopg/raw_cursor.py @@ -6,8 +6,7 @@ psycopg raw queries cursors from __future__ import annotations -from typing import Any, TYPE_CHECKING - +from typing import TYPE_CHECKING from .abc import ConnectionType, Query, Params from .sql import Composable from .rows import Row @@ -18,8 +17,9 @@ from ._queries import PostgresQuery from ._cursor_base import BaseCursor if TYPE_CHECKING: - from .connection import Connection - from .connection_async import AsyncConnection + from typing import Any # noqa: F401 + from .connection import Connection # noqa: F401 + from .connection_async import AsyncConnection # noqa: F401 class PostgresRawQuery(PostgresQuery): @@ -54,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 1a4bbd538..cb67f7f07 100644 --- a/psycopg/psycopg/rows.py +++ b/psycopg/psycopg/rows.py @@ -81,13 +81,13 @@ class BaseRowFactory(Protocol[Row]): def __call__(self, __cursor: BaseCursor[Any, Any]) -> RowMaker[Row]: ... -TupleRow: TypeAlias = tuple[Any, ...] +TupleRow: TypeAlias = "tuple[Any, ...]" """ An alias for the type returned by `tuple_row()` (i.e. a tuple of any content). """ -DictRow: TypeAlias = dict[str, Any] +DictRow: TypeAlias = "dict[str, Any]" """ An alias for the type returned by `dict_row()` diff --git a/psycopg/psycopg/server_cursor.py b/psycopg/psycopg/server_cursor.py index a75281bfb..c1492b386 100644 --- a/psycopg/psycopg/server_cursor.py +++ b/psycopg/psycopg/server_cursor.py @@ -211,7 +211,7 @@ 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__ = () @@ -348,7 +348,9 @@ 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__ = () diff --git a/psycopg/psycopg/transaction.py b/psycopg/psycopg/transaction.py index 2d352445d..9a60a5fbc 100644 --- a/psycopg/psycopg/transaction.py +++ b/psycopg/psycopg/transaction.py @@ -227,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. """ @@ -257,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. """ diff --git a/psycopg/psycopg/types/array.py b/psycopg/psycopg/types/array.py index ea8dfd316..59a09ab54 100644 --- a/psycopg/psycopg/types/array.py +++ b/psycopg/psycopg/types/array.py @@ -24,10 +24,12 @@ from .._typeinfo import TypeInfo _struct_head = struct.Struct("!III") # ndims, hasnull, elem oid _pack_head = cast(Callable[[int, int, int], bytes], _struct_head.pack) -_unpack_head = cast(Callable[[Buffer], tuple[int, int, int]], _struct_head.unpack_from) +_unpack_head = cast( + Callable[[Buffer], "tuple[int, int, int]"], _struct_head.unpack_from +) _struct_dim = struct.Struct("!II") # dim, lower bound _pack_dim = cast(Callable[[int, int], bytes], _struct_dim.pack) -_unpack_dim = cast(Callable[[Buffer, int], tuple[int, int]], _struct_dim.unpack_from) +_unpack_dim = cast(Callable[[Buffer, int], "tuple[int, int]"], _struct_dim.unpack_from) PY_TEXT = PyFormat.TEXT PQ_BINARY = pq.Format.BINARY diff --git a/psycopg/psycopg/types/composite.py b/psycopg/psycopg/types/composite.py index 4a770d125..576529a05 100644 --- a/psycopg/psycopg/types/composite.py +++ b/psycopg/psycopg/types/composite.py @@ -29,7 +29,7 @@ if TYPE_CHECKING: _struct_oidlen = struct.Struct("!Ii") _pack_oidlen = cast(Callable[[int, int], bytes], _struct_oidlen.pack) _unpack_oidlen = cast( - Callable[[abc.Buffer, int], tuple[int, int]], _struct_oidlen.unpack_from + Callable[[abc.Buffer, int], "tuple[int, int]"], _struct_oidlen.unpack_from ) diff --git a/psycopg/psycopg/types/datetime.py b/psycopg/psycopg/types/datetime.py index b701a0205..866a2fa6c 100644 --- a/psycopg/psycopg/types/datetime.py +++ b/psycopg/psycopg/types/datetime.py @@ -24,12 +24,12 @@ if TYPE_CHECKING: _struct_timetz = struct.Struct("!qi") # microseconds, sec tz offset _pack_timetz = cast(Callable[[int, int], bytes], _struct_timetz.pack) -_unpack_timetz = cast(Callable[[Buffer], tuple[int, int]], _struct_timetz.unpack) +_unpack_timetz = cast(Callable[[Buffer], "tuple[int, int]"], _struct_timetz.unpack) _struct_interval = struct.Struct("!qii") # microseconds, days, months _pack_interval = cast(Callable[[int, int, int], bytes], _struct_interval.pack) _unpack_interval = cast( - Callable[[Buffer], tuple[int, int, int]], _struct_interval.unpack + Callable[[Buffer], "tuple[int, int, int]"], _struct_interval.unpack ) utc = timezone.utc diff --git a/psycopg/psycopg/types/enum.py b/psycopg/psycopg/types/enum.py index 65a75d1bd..82e7f174c 100644 --- a/psycopg/psycopg/types/enum.py +++ b/psycopg/psycopg/types/enum.py @@ -22,13 +22,13 @@ if TYPE_CHECKING: E = TypeVar("E", bound=Enum) -EnumDumpMap: TypeAlias = dict[E, bytes] -EnumLoadMap: TypeAlias = dict[bytes, E] -EnumMapping: TypeAlias = Mapping[E, str] | Sequence[tuple[E, str]] | None +EnumDumpMap: TypeAlias = "dict[E, bytes]" +EnumLoadMap: TypeAlias = "dict[bytes, E]" +EnumMapping: TypeAlias = "Mapping[E, str] | Sequence[tuple[E, str]] | None" # Hashable versions -_HEnumDumpMap: TypeAlias = tuple[tuple[E, bytes], ...] -_HEnumLoadMap: TypeAlias = tuple[tuple[bytes, E], ...] +_HEnumDumpMap: TypeAlias = "tuple[tuple[E, bytes], ...]" +_HEnumLoadMap: TypeAlias = "tuple[tuple[bytes, E], ...]" TEXT = Format.TEXT BINARY = Format.BINARY @@ -142,7 +142,7 @@ def register_enum( raise TypeError("no info passed. Is the requested enum available?") if enum is None: - enum = cast(type[E], _make_enum(info.name, tuple(info.labels))) + enum = cast("type[E]", _make_enum(info.name, tuple(info.labels))) info.enum = enum adapters = context.adapters if context else postgres.adapters diff --git a/psycopg/psycopg/types/hstore.py b/psycopg/psycopg/types/hstore.py index ad368d353..55944c148 100644 --- a/psycopg/psycopg/types/hstore.py +++ b/psycopg/psycopg/types/hstore.py @@ -36,7 +36,7 @@ _re_hstore = re.compile( ) -Hstore: TypeAlias = dict[str, str | None] +Hstore: TypeAlias = "dict[str, str | None]" class BaseHstoreDumper(RecursiveDumper): diff --git a/psycopg/psycopg/types/json.py b/psycopg/psycopg/types/json.py index 47e85fff6..56ac23418 100644 --- a/psycopg/psycopg/types/json.py +++ b/psycopg/psycopg/types/json.py @@ -15,10 +15,10 @@ from .. import errors as e from ..pq import Format from ..adapt import Buffer, Dumper, Loader, PyFormat, AdaptersMap from ..errors import DataError -from .._compat import cache +from .._compat import cache, TypeAlias -JsonDumpsFunction = Callable[[Any], str | bytes] -JsonLoadsFunction = Callable[[str | bytes], Any] +JsonDumpsFunction: TypeAlias = Callable[[Any], "str | bytes"] +JsonLoadsFunction: TypeAlias = Callable[["str | bytes"], Any] def set_json_dumps( diff --git a/psycopg/psycopg/types/net.py b/psycopg/psycopg/types/net.py index 4cbe0b3d6..67f6adb4b 100644 --- a/psycopg/psycopg/types/net.py +++ b/psycopg/psycopg/types/net.py @@ -17,9 +17,9 @@ from .._compat import TypeAlias if TYPE_CHECKING: import ipaddress -Address: TypeAlias = "ipaddress.IPv4Address" | "ipaddress.IPv6Address" -Interface: TypeAlias = "ipaddress.IPv4Interface" | "ipaddress.IPv6Interface" -Network: TypeAlias = "ipaddress.IPv4Network" | "ipaddress.IPv6Network" +Address: TypeAlias = "ipaddress.IPv4Address | ipaddress.IPv6Address" +Interface: TypeAlias = "ipaddress.IPv4Interface | ipaddress.IPv6Interface" +Network: TypeAlias = "ipaddress.IPv4Network | ipaddress.IPv6Network" # These objects will be imported lazily ip_address: Callable[[str], Address] = None # type: ignore[assignment] diff --git a/psycopg/psycopg/types/numeric.py b/psycopg/psycopg/types/numeric.py index 65bd10989..f3a108543 100644 --- a/psycopg/psycopg/types/numeric.py +++ b/psycopg/psycopg/types/numeric.py @@ -315,7 +315,7 @@ for i in range(DefaultContext.prec): _contexts[i] = DefaultContext _unpack_numeric_head = cast( - Callable[[Buffer], tuple[int, int, int, int]], + Callable[[Buffer], "tuple[int, int, int, int]"], struct.Struct("!HhHH").unpack_from, ) _pack_numeric_head = cast( diff --git a/psycopg_pool/psycopg_pool/abc.py b/psycopg_pool/psycopg_pool/abc.py index d3ffccf3d..492917dc0 100644 --- a/psycopg_pool/psycopg_pool/abc.py +++ b/psycopg_pool/psycopg_pool/abc.py @@ -6,13 +6,14 @@ Types used in the psycopg_pool package from __future__ import annotations -from typing import Any, Awaitable, Callable, TYPE_CHECKING +from typing import Awaitable, Callable, TYPE_CHECKING from ._compat import TypeAlias, TypeVar if TYPE_CHECKING: - from .pool import ConnectionPool - from .pool_async import AsyncConnectionPool + from typing import Any # noqa: F401 + from .pool import ConnectionPool # noqa: F401 + from .pool_async import AsyncConnectionPool # noqa: F401 from psycopg import Connection, AsyncConnection # noqa: F401 from psycopg.rows import TupleRow # noqa: F401 @@ -25,8 +26,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/null_pool.py b/psycopg_pool/psycopg_pool/null_pool.py index 2e48e470e..fb071b594 100644 --- a/psycopg_pool/psycopg_pool/null_pool.py +++ b/psycopg_pool/psycopg_pool/null_pool.py @@ -31,7 +31,7 @@ class NullConnectionPool(_BaseNullConnectionPool, ConnectionPool[CT]): self, conninfo: str = "", *, - connection_class: type[CT] = cast(type[CT], Connection), + connection_class: type[CT] = cast("type[CT]", Connection), kwargs: dict[str, Any] | None = None, min_size: int = 0, max_size: int | None = None, diff --git a/psycopg_pool/psycopg_pool/null_pool_async.py b/psycopg_pool/psycopg_pool/null_pool_async.py index 7de17e752..f89aa2ed8 100644 --- a/psycopg_pool/psycopg_pool/null_pool_async.py +++ b/psycopg_pool/psycopg_pool/null_pool_async.py @@ -27,7 +27,7 @@ class AsyncNullConnectionPool(_BaseNullConnectionPool, AsyncConnectionPool[ACT]) self, conninfo: str = "", *, - connection_class: type[ACT] = cast(type[ACT], AsyncConnection), + connection_class: type[ACT] = cast("type[ACT]", AsyncConnection), kwargs: dict[str, Any] | None = None, min_size: int = 0, # Note: min_size default value changed to 0. max_size: int | None = None, diff --git a/psycopg_pool/psycopg_pool/pool.py b/psycopg_pool/psycopg_pool/pool.py index 881832d39..96d81b9a8 100644 --- a/psycopg_pool/psycopg_pool/pool.py +++ b/psycopg_pool/psycopg_pool/pool.py @@ -41,7 +41,7 @@ class ConnectionPool(Generic[CT], BasePool): self, conninfo: str = "", *, - connection_class: type[CT] = cast(type[CT], Connection), + connection_class: type[CT] = cast("type[CT]", Connection), kwargs: dict[str, Any] | None = None, min_size: int = 4, max_size: int | None = None, diff --git a/psycopg_pool/psycopg_pool/pool_async.py b/psycopg_pool/psycopg_pool/pool_async.py index 4914f6685..48147bdf5 100644 --- a/psycopg_pool/psycopg_pool/pool_async.py +++ b/psycopg_pool/psycopg_pool/pool_async.py @@ -40,7 +40,7 @@ class AsyncConnectionPool(Generic[ACT], BasePool): self, conninfo: str = "", *, - connection_class: type[ACT] = cast(type[ACT], AsyncConnection), + connection_class: type[ACT] = cast("type[ACT]", AsyncConnection), kwargs: dict[str, Any] | None = None, min_size: int = 4, max_size: int | None = None, diff --git a/tests/pool/test_pool.py b/tests/pool/test_pool.py index 4a9675749..d5946f2d4 100644 --- a/tests/pool/test_pool.py +++ b/tests/pool/test_pool.py @@ -6,7 +6,7 @@ from __future__ import annotations import logging import weakref from time import time -from typing import Any +from typing import Any, Dict import pytest @@ -43,7 +43,7 @@ def test_bad_size(dsn, min_size, max_size): pool.ConnectionPool(min_size=min_size, max_size=max_size) -class MyRow(dict[str, Any]): +class MyRow(Dict[str, Any]): pass diff --git a/tests/pool/test_pool_async.py b/tests/pool/test_pool_async.py index 8f522a6f4..160d7119d 100644 --- a/tests/pool/test_pool_async.py +++ b/tests/pool/test_pool_async.py @@ -3,7 +3,7 @@ from __future__ import annotations import logging import weakref from time import time -from typing import Any +from typing import Any, Dict import pytest @@ -43,7 +43,7 @@ async def test_bad_size(dsn, min_size, max_size): pool.AsyncConnectionPool(min_size=min_size, max_size=max_size) -class MyRow(dict[str, Any]): +class MyRow(Dict[str, Any]): pass diff --git a/tests/pool/test_pool_null.py b/tests/pool/test_pool_null.py index 13260ad0d..89b39d7af 100644 --- a/tests/pool/test_pool_null.py +++ b/tests/pool/test_pool_null.py @@ -4,7 +4,7 @@ from __future__ import annotations import logging -from typing import Any +from typing import Any, Dict import pytest from packaging.version import parse as ver # noqa: F401 # used in skipif @@ -41,7 +41,7 @@ def test_bad_size(dsn, min_size, max_size): pool.NullConnectionPool(min_size=min_size, max_size=max_size) -class MyRow(dict[str, Any]): +class MyRow(Dict[str, Any]): pass diff --git a/tests/pool/test_pool_null_async.py b/tests/pool/test_pool_null_async.py index c35cacba3..c74acb8fd 100644 --- a/tests/pool/test_pool_null_async.py +++ b/tests/pool/test_pool_null_async.py @@ -1,7 +1,7 @@ from __future__ import annotations import logging -from typing import Any +from typing import Any, Dict import pytest from packaging.version import parse as ver # noqa: F401 # used in skipif @@ -41,7 +41,7 @@ async def test_bad_size(dsn, min_size, max_size): pool.AsyncNullConnectionPool(min_size=min_size, max_size=max_size) -class MyRow(dict[str, Any]): +class MyRow(Dict[str, Any]): pass diff --git a/tests/test_pipeline.py b/tests/test_pipeline.py index 8d1fb0279..89abdbf53 100644 --- a/tests/test_pipeline.py +++ b/tests/test_pipeline.py @@ -1,6 +1,8 @@ # WARNING: this file is auto-generated by 'async_to_sync.py' # from the original file 'test_pipeline_async.py' # DO NOT CHANGE! Change the original file instead. +from __future__ import annotations + import logging from typing import Any from operator import attrgetter diff --git a/tests/test_pipeline_async.py b/tests/test_pipeline_async.py index b9baa589f..c50413b83 100644 --- a/tests/test_pipeline_async.py +++ b/tests/test_pipeline_async.py @@ -1,3 +1,5 @@ +from __future__ import annotations + import logging from typing import Any from operator import attrgetter diff --git a/tests/test_psycopg_dbapi20.py b/tests/test_psycopg_dbapi20.py index 982929e07..aa4309734 100644 --- a/tests/test_psycopg_dbapi20.py +++ b/tests/test_psycopg_dbapi20.py @@ -1,3 +1,5 @@ +from __future__ import annotations + import pytest import datetime as dt from typing import Any diff --git a/tools/async_to_sync.py b/tools/async_to_sync.py index 989181a08..41d88fa5b 100755 --- a/tools/async_to_sync.py +++ b/tools/async_to_sync.py @@ -349,6 +349,14 @@ class RenameAsyncToSync(ast.NodeTransformer): # type: ignore self.generic_visit(node) return node + def visit_Call(self, node: ast.Call) -> ast.AST: + match node: + case ast.Call(func=ast.Name(id="cast")): + node.args[0] = self._convert_if_literal_string(node.args[0]) + + self.generic_visit(node) + return node + def visit_FunctionDef(self, node: ast.FunctionDef) -> ast.AST: self._fix_docstring(node.body) if node.decorator_list: