]> git.ipfire.org Git - thirdparty/psycopg.git/commitdiff
Add Generic Counter and Deque to compat module
authorDaniele Varrazzo <daniele.varrazzo@gmail.com>
Mon, 8 Nov 2021 15:00:18 +0000 (16:00 +0100)
committerDaniele Varrazzo <daniele.varrazzo@gmail.com>
Mon, 8 Nov 2021 15:00:18 +0000 (16:00 +0100)
psycopg/psycopg/_compat.py
psycopg_pool/psycopg_pool/base.py
psycopg_pool/psycopg_pool/pool.py
psycopg_pool/psycopg_pool/pool_async.py
tests/fix_faker.py
tests/pool/test_pool.py
tests/pool/test_pool_async.py

index 7dd0113700fba6ca2de135cf7113aa66d011964d..0576b71ad6bdac45f7684e888d7c2a2f413b89bb 100644 (file)
@@ -51,10 +51,14 @@ else:
 
 if sys.version_info >= (3, 9):
     from zoneinfo import ZoneInfo
+    from collections import Counter, deque as Deque
 else:
     from backports.zoneinfo import ZoneInfo
+    from typing import Counter, Deque
 
 __all__ = [
+    "Counter",
+    "Deque",
     "Protocol",
     "ZoneInfo",
     "asynccontextmanager",
index 0227b2e0dd70635bd15f8777b9762302b56d6cf3..afb4bc533318579610b65c27c29777856b82e128 100644 (file)
@@ -5,14 +5,10 @@ psycopg connection pool base class and functionalities.
 # Copyright (C) 2021 The Psycopg Team
 
 from random import random
-from typing import Any, Callable, Deque, Dict, Generic, Optional
-from typing import TYPE_CHECKING
-from collections import Counter, deque
+from typing import Any, Callable, Dict, Generic, Optional
 
 from psycopg.abc import ConnectionType
-
-if TYPE_CHECKING:
-    from typing import Counter as TCounter
+from psycopg._compat import Counter, Deque
 
 
 class BasePool(Generic[ConnectionType]):
@@ -81,8 +77,8 @@ class BasePool(Generic[ConnectionType]):
         self.num_workers = num_workers
 
         self._nconns = min_size  # currently in the pool, out, being prepared
-        self._pool: Deque[ConnectionType] = deque()
-        self._stats: "TCounter[str]" = Counter()
+        self._pool = Deque[ConnectionType]()
+        self._stats = Counter[str]()
 
         # Min number of connections in the pool in a max_idle unit of time.
         # It is reset periodically by the ShrinkPool scheduled task.
index e52b5e0476636d9e8257afc675b5076129371330..27cc35fb774b35b2833fd8a9a1b632ed144b3e83 100644 (file)
@@ -10,15 +10,15 @@ from abc import ABC, abstractmethod
 from time import monotonic
 from queue import Queue, Empty
 from types import TracebackType
-from typing import Any, Callable, Deque, Dict, Iterator, List
+from typing import Any, Callable, Dict, Iterator, List
 from typing import Optional, Type
 from weakref import ref
 from contextlib import contextmanager
-from collections import deque
 
 from psycopg import errors as e
 from psycopg import Connection
 from psycopg.pq import TransactionStatus
+from psycopg._compat import Deque
 
 from .base import ConnectionAttempt, BasePool
 from .sched import Scheduler
@@ -42,7 +42,7 @@ class ConnectionPool(BasePool[Connection[Any]]):
         self._reset = reset
 
         self._lock = threading.RLock()
-        self._waiting: Deque["WaitingClient"] = deque()
+        self._waiting = Deque["WaitingClient"]()
 
         # to notify that the pool is full
         self._pool_full_event: Optional[threading.Event] = None
@@ -534,8 +534,6 @@ class ConnectionPool(BasePool[Connection[Any]]):
         # Also disable the warning for open connection in conn.__del__
         conn._pool = None
 
-        pos: Optional[WaitingClient] = None
-
         # Critical section: if there is a client waiting give it the connection
         # otherwise put it back into the pool.
         with self._lock:
index 965e930b2b1138ada16eaab7799f22c4df024fd7..ae161297812c66b5b61a83d3bf3d6e296885b985 100644 (file)
@@ -10,14 +10,13 @@ import logging
 from abc import ABC, abstractmethod
 from time import monotonic
 from types import TracebackType
-from typing import Any, AsyncIterator, Awaitable, Callable, Deque
+from typing import Any, AsyncIterator, Awaitable, Callable
 from typing import Dict, List, Optional, Type
 from weakref import ref
-from collections import deque
 
 from psycopg import errors as e
 from psycopg.pq import TransactionStatus
-from psycopg._compat import Task, asynccontextmanager, create_task
+from psycopg._compat import Task, asynccontextmanager, create_task, Deque
 from psycopg.connection_async import AsyncConnection
 
 from .base import ConnectionAttempt, BasePool
@@ -52,7 +51,7 @@ class AsyncConnectionPool(BasePool[AsyncConnection[Any]]):
         self._reset = reset
 
         self._lock = asyncio.Lock()
-        self._waiting: Deque["AsyncClient"] = deque()
+        self._waiting = Deque["AsyncClient"]()
 
         # to notify that the pool is full
         self._pool_full_event: Optional[asyncio.Event] = None
@@ -464,8 +463,6 @@ class AsyncConnectionPool(BasePool[AsyncConnection[Any]]):
         # Also disable the warning for open connection in conn.__del__
         conn._pool = None
 
-        pos: Optional[AsyncClient] = None
-
         # Critical section: if there is a client waiting give it the connection
         # otherwise put it back into the pool.
         async with self._lock:
index 8a9a3529da525f04781c9233e4ac1233a55ec983..1885e161a0c8fd0d169b22840a9c58d502e9df26 100644 (file)
@@ -6,14 +6,13 @@ from uuid import UUID
 from random import choice, random, randrange
 from decimal import Decimal
 from contextlib import contextmanager
-from collections import deque
 
 import pytest
 
 import psycopg
 from psycopg import sql
 from psycopg.adapt import PyFormat
-from psycopg._compat import asynccontextmanager
+from psycopg._compat import asynccontextmanager, Deque
 from psycopg.types.range import Range
 from psycopg.types.numeric import Int4, Int8
 from psycopg.types.multirange import Multirange
@@ -833,7 +832,7 @@ class JsonFloat:
 
 
 def deep_import(name):
-    parts = deque(name.split("."))
+    parts = Deque(name.split("."))
     seen = []
     if not parts:
         raise ValueError("name must be a dot-separated name")
index 22353d750aa1579ca53a4bf90692a9a02b446b09..dfeca1d817aabb12d585f7495c226cb2849858d4 100644 (file)
@@ -3,13 +3,13 @@ import logging
 import weakref
 from time import sleep, time
 from threading import Thread, Event
-from collections import Counter
 from typing import Any, List, Tuple
 
 import pytest
 
 import psycopg
 from psycopg.pq import TransactionStatus
+from psycopg._compat import Counter
 
 pytestmark = []
 
@@ -817,7 +817,7 @@ def test_uniform_use(dsn, retries):
     for retry in retries:
         with retry:
             with pool.ConnectionPool(dsn, min_size=4) as p:
-                counts = Counter()  # type: Counter[int]
+                counts = Counter[int]()
                 for i in range(8):
                     with p.connection() as conn:
                         sleep(0.1)
index 6bc68f25cc6e8617c05c5e226348736ea38b1af2..a05fe82838caa0ea706f42383b150a91a0c34936 100644 (file)
@@ -2,14 +2,13 @@ import sys
 import asyncio
 import logging
 from time import time
-from collections import Counter
 from typing import Any, List, Tuple
 
 import pytest
 
 import psycopg
 from psycopg.pq import TransactionStatus
-from psycopg._compat import create_task
+from psycopg._compat import create_task, Counter
 
 pytestmark = [
     pytest.mark.asyncio,
@@ -812,7 +811,7 @@ async def test_uniform_use(dsn, retries):
     async for retry in retries:
         with retry:
             async with pool.AsyncConnectionPool(dsn, min_size=4) as p:
-                counts = Counter()  # type: Counter[int]
+                counts = Counter[int]()
                 for i in range(8):
                     async with p.connection() as conn:
                         await asyncio.sleep(0.1)