]> git.ipfire.org Git - thirdparty/psycopg.git/commitdiff
fix: fix type annotation for Python 3.8 832/head
authorDaniele Varrazzo <daniele.varrazzo@gmail.com>
Thu, 30 May 2024 03:28:59 +0000 (05:28 +0200)
committerDaniele Varrazzo <daniele.varrazzo@gmail.com>
Tue, 4 Jun 2024 14:52:16 +0000 (16:52 +0200)
40 files changed:
psycopg/psycopg/_adapters_map.py
psycopg/psycopg/_copy.py
psycopg/psycopg/_copy_async.py
psycopg/psycopg/_pipeline.py
psycopg/psycopg/_preparing.py
psycopg/psycopg/_py_transformer.py
psycopg/psycopg/_queries.py
psycopg/psycopg/_struct.py
psycopg/psycopg/abc.py
psycopg/psycopg/client_cursor.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/raw_cursor.py
psycopg/psycopg/rows.py
psycopg/psycopg/server_cursor.py
psycopg/psycopg/transaction.py
psycopg/psycopg/types/array.py
psycopg/psycopg/types/composite.py
psycopg/psycopg/types/datetime.py
psycopg/psycopg/types/enum.py
psycopg/psycopg/types/hstore.py
psycopg/psycopg/types/json.py
psycopg/psycopg/types/net.py
psycopg/psycopg/types/numeric.py
psycopg_pool/psycopg_pool/abc.py
psycopg_pool/psycopg_pool/null_pool.py
psycopg_pool/psycopg_pool/null_pool_async.py
psycopg_pool/psycopg_pool/pool.py
psycopg_pool/psycopg_pool/pool_async.py
tests/pool/test_pool.py
tests/pool/test_pool_async.py
tests/pool/test_pool_null.py
tests/pool/test_pool_null_async.py
tests/test_pipeline.py
tests/test_pipeline_async.py
tests/test_psycopg_dbapi20.py
tools/async_to_sync.py

index 53e1b583b94704b93b54bb9b75297dde7312e777..c633b6bef137324ce110d472853c4347bd659d3b 100644 (file)
@@ -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
index 092d9635aeb31d20a54f5c4ff43e51ffce07e224..1c393a9d632925f4ab4079930a3683d0b071bfef 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
+    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.
index 6cddac413592e45c9f8866b3a1ea49b748fb8d3b..2c630da9b96d7b12d7c56d46f660e4de41b521dd 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
+    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.
index 9b64572180f544edf181944d01b2406f58b240fa..441b2147c7a0f7e4db8cce7a4abf52a9f646d5a3 100644 (file)
@@ -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
index 4face76876d0a821ed212ea5ab2cc7afb196531e..c48c86c09254810b7e1ebdbd3791dd1bc7e04089 100644 (file)
@@ -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:
index c2f4ea21cc5eea775a586dbfb6ad9f8ac05fd343..0620113eecc5e4366fd74682bd65980d44cb660c 100644 (file)
@@ -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
index 0cd615b6a3e0e9d8d635a7e0f5f59e19a2d9fd23..537a656694c53ab54241348cbcb025e9da750843 100644 (file)
@@ -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]]"
 ]
 
 
index a09f8b53590ee9e1f625633d7f7fbcc0cc4b4643..01978a500d20e8d501d0cd57f0b978ae5649baaa 100644 (file)
@@ -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):
index e5e02d7e6e55d2e08e1ba7a82b7eed662ea22617..edac47c2a7a0140e704cbe18d00966ab0650324f 100644 (file)
@@ -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]
 
 
index 058d0fe62a374c98669068dffc3291fd363443fe..5a64e5fe77b26ef88ef23b7edc125c7d81e1d9a0 100644 (file)
@@ -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"
index fdcd7e66e413cc82ab989745f9ae99106a940cdb..6d1ddf01928832237702d533297bbaf9c5cc4512 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 c07fccc7f02f48c8016867862e36004f42a35f14..b708d5d6c6960284831bc3124a2c9639fbd61aa6 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 f6b1410c4a22670c0307e81364436a5fb29fba8b..0d162feaa9af08ba0f6382bc316e4bad4d1abc6d 100644 (file)
@@ -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]] = {}
 
index 9d1d36389e10de36ef04304f61b1b7af6b2d5d7a..70855c55d08a2fabd491a79f10dde33023102d60 100644 (file)
@@ -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")
index 4bf350934d479ca17cb4cbdf6814ed6510b907cc..cd3fdbf5d0d4da49f1d2d9f5f0af486a9c25e052 100644 (file)
@@ -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):
index 00c6aa20c2ddbbfc8c241a82c05fe52fe50f39b0..03c1903c0d2a7c5636e6425a3966c768f52bb8a8 100644 (file)
@@ -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"
index 1a4bbd538546f45360fb2d4ef3f6e1f72695a83c..cb67f7f0781bb56bedbbce86025369926d3cf69c 100644 (file)
@@ -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()`
 
index a75281bfba6abb3cc3c11f574cc15bf06af74ac5..c1492b38693fbf5ca03576afaf701ca4cd71fb2e 100644 (file)
@@ -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__ = ()
 
index 2d352445df407466af0802a5d306defca908b83a..9a60a5fbc6bce3b9700a9a8c71b8439c0e90161b 100644 (file)
@@ -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.
     """
index ea8dfd31616198f7cf0632ce48aab353bcb93ffc..59a09ab545de098ee9947510e5aca69abd352798 100644 (file)
@@ -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
index 4a770d125800f0889d82d56abc8c22aa3803c999..576529a0538da6770c53458a288fa8c1b78ece6d 100644 (file)
@@ -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
 )
 
 
index b701a020571e2d0c4ac61591ad335e859c434ee7..866a2fa6cbde72befae0cb62098097b64805190f 100644 (file)
@@ -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
index 65a75d1bd0b40db58c3071f242d9ecf53d705888..82e7f174ca5bd0303b1224f5153fa6a32d463b8f 100644 (file)
@@ -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
index ad368d353d31549b17f5bd221bb4e007223b4ac0..55944c1488b07502aa04b12eea60fb716932720c 100644 (file)
@@ -36,7 +36,7 @@ _re_hstore = re.compile(
 )
 
 
-Hstore: TypeAlias = dict[str, str | None]
+Hstore: TypeAlias = "dict[str, str | None]"
 
 
 class BaseHstoreDumper(RecursiveDumper):
index 47e85fff6ef1702288744aa27279dcfb6a25fbbc..56ac23418542e252d4978a57ca62e4513bf03c00 100644 (file)
@@ -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(
index 4cbe0b3d683543350dc1896336851536f1873ec7..67f6adb4b27002e91b47209c0c0fd87608461d6b 100644 (file)
@@ -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]
index 65bd109892c94e938a87405715ca4596797d8472..f3a1085436e1b46857e893f27ef56be80241a568 100644 (file)
@@ -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(
index d3ffccf3d6f846ccdbb8bbe4c81b2f7fc351c92b..492917dc0f1a852fd4705e8a38470834dabecc8e 100644 (file)
@@ -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]]"
 )
index 2e48e470e624904dc147222e8916d2fe8ed301a2..fb071b594517b7d631f92399dc66f9c397a64a02 100644 (file)
@@ -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,
index 7de17e752d258a9380f0024ed427540f1aa158aa..f89aa2ed8c68eaffe1943f35af33fefac7554616 100644 (file)
@@ -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,
index 881832d397d970c4490d2633999c61b1a089cabd..96d81b9a8114c7ce8891b1a3d0d416994ee1f44a 100644 (file)
@@ -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,
index 4914f66858916d52a4c2792da84b0f70a807b48a..48147bdf54203431d4df9b55402d7ffba93e0ec9 100644 (file)
@@ -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,
index 4a967574907317f1e0e8e26a9969cd7eee94df21..d5946f2d4d3ea902642b699dfaa16f192bdabb35 100644 (file)
@@ -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
 
 
index 8f522a6f4c7bd26bfaa84bcb4d7d209cf5a52fcb..160d7119d6fd5027d67d74cd341e70baf8e60f15 100644 (file)
@@ -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
 
 
index 13260ad0d6776bec338d8fdafd6a8648fb019e4a..89b39d7af36e6d410003dd1b2fb10e2881c8db29 100644 (file)
@@ -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
 
 
index c35cacba3c072c83c7c8c0d7f2f34c2e5724245d..c74acb8fdfd5201179294ad8108d3b0588f3206a 100644 (file)
@@ -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
 
 
index 8d1fb02797ecf5a26487aaeb76bfacb373c53a70..89abdbf533b1d30677c4176e2b7218c1a4831587 100644 (file)
@@ -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
index b9baa589f4ae92388f0d9cc72547b967fad49585..c50413b836a5e8dea54e48506fb3459b6aa804e9 100644 (file)
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
 import logging
 from typing import Any
 from operator import attrgetter
index 982929e07e6f71e8b365be3809a5f7e463eba4ec..aa4309734143cd7c605c0de8bcd571c3d6340bb6 100644 (file)
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
 import pytest
 import datetime as dt
 from typing import Any
index 989181a0840770b28c5400898fd7aed697412a90..41d88fa5b962a4cc8c1b4cb4d6914e87a7e94647 100755 (executable)
@@ -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: