|
| 1 | +"""Compatibility shims for Python versions older than 3.10.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import sys |
| 6 | +from collections.abc import AsyncIterator |
| 7 | +from typing import TYPE_CHECKING, Any |
| 8 | + |
| 9 | +if TYPE_CHECKING: |
| 10 | + from importlib.metadata import EntryPoint |
| 11 | + |
| 12 | +if sys.version_info >= (3, 10): |
| 13 | + import asyncio |
| 14 | + import importlib.metadata |
| 15 | + from contextlib import aclosing |
| 16 | + |
| 17 | + def entry_points_group(group: str) -> list[EntryPoint]: |
| 18 | + """Entry points for ``group`` (`entry_points(group=...)` needs 3.10+).""" |
| 19 | + # Resolved dynamically so tests can monkeypatch importlib.metadata.entry_points. |
| 20 | + return list(importlib.metadata.entry_points(group=group)) |
| 21 | + |
| 22 | + AsyncLock = asyncio.Lock |
| 23 | + AsyncEvent = asyncio.Event |
| 24 | + AsyncSemaphore = asyncio.Semaphore |
| 25 | + AsyncQueue = asyncio.Queue |
| 26 | + |
| 27 | +else: |
| 28 | + import asyncio |
| 29 | + import collections |
| 30 | + import importlib.metadata |
| 31 | + from contextlib import asynccontextmanager |
| 32 | + |
| 33 | + @asynccontextmanager |
| 34 | + async def aclosing(thing: Any) -> AsyncIterator[Any]: |
| 35 | + try: |
| 36 | + yield thing |
| 37 | + finally: |
| 38 | + await thing.aclose() |
| 39 | + |
| 40 | + def entry_points_group(group: str) -> list[EntryPoint]: |
| 41 | + """Entry points for ``group`` (`entry_points(group=...)` needs 3.10+).""" |
| 42 | + # Resolved dynamically so tests can monkeypatch importlib.metadata.entry_points. |
| 43 | + eps = importlib.metadata.entry_points() |
| 44 | + if isinstance(eps, dict): # 3.9 returns {group: [EntryPoint, ...]} |
| 45 | + return list(eps.get(group, [])) |
| 46 | + return list(eps) |
| 47 | + |
| 48 | + class _LazyLoopMixin: |
| 49 | + """Defer event-loop binding to first use inside a running loop. |
| 50 | +
|
| 51 | + Python 3.9's asyncio primitives call ``get_event_loop()`` eagerly in |
| 52 | + ``__init__``, which (a) raises when constructed in a sync context with |
| 53 | + no loop set, and (b) binds to a loop that may not be the one the |
| 54 | + primitive is later awaited in. Python 3.10 made binding lazy; these |
| 55 | + subclasses backport that behavior by skipping the eager binding and |
| 56 | + resolving ``self._loop`` at first use via a property. |
| 57 | + """ |
| 58 | + |
| 59 | + _lazy_loop: Any = None |
| 60 | + |
| 61 | + @property |
| 62 | + def _loop(self) -> Any: |
| 63 | + loop = asyncio.get_running_loop() |
| 64 | + if self._lazy_loop is None: |
| 65 | + self._lazy_loop = loop |
| 66 | + if self._lazy_loop is not loop: |
| 67 | + raise RuntimeError(f"{self!r} is bound to a different event loop") |
| 68 | + return loop |
| 69 | + |
| 70 | + class AsyncLock(_LazyLoopMixin, asyncio.Lock): |
| 71 | + def __init__(self) -> None: |
| 72 | + # State from 3.9 Lock.__init__, minus the eager loop binding. |
| 73 | + self._waiters = None |
| 74 | + self._locked = False |
| 75 | + |
| 76 | + class AsyncEvent(_LazyLoopMixin, asyncio.Event): |
| 77 | + def __init__(self) -> None: |
| 78 | + # State from 3.9 Event.__init__, minus the eager loop binding. |
| 79 | + self._waiters = collections.deque() |
| 80 | + self._value = False |
| 81 | + |
| 82 | + class AsyncSemaphore(_LazyLoopMixin, asyncio.Semaphore): |
| 83 | + def __init__(self, value: int = 1) -> None: |
| 84 | + # State from 3.9 Semaphore.__init__, minus the eager loop binding. |
| 85 | + if value < 0: |
| 86 | + raise ValueError("Semaphore initial value must be >= 0") |
| 87 | + self._value = value |
| 88 | + self._waiters = collections.deque() |
| 89 | + self._wakeup_scheduled = False |
| 90 | + |
| 91 | + class AsyncQueue(_LazyLoopMixin, asyncio.Queue): |
| 92 | + def __init__(self, maxsize: int = 0) -> None: |
| 93 | + # State from 3.9 Queue.__init__, minus the eager loop binding. |
| 94 | + self._maxsize = maxsize |
| 95 | + self._getters: collections.deque[Any] = collections.deque() |
| 96 | + self._putters: collections.deque[Any] = collections.deque() |
| 97 | + self._unfinished_tasks = 0 |
| 98 | + self._finished = AsyncEvent() |
| 99 | + self._finished.set() |
| 100 | + self._init(maxsize) |
| 101 | + |
| 102 | + |
| 103 | +__all__ = [ |
| 104 | + "AsyncEvent", |
| 105 | + "AsyncLock", |
| 106 | + "AsyncQueue", |
| 107 | + "AsyncSemaphore", |
| 108 | + "aclosing", |
| 109 | + "entry_points_group", |
| 110 | +] |
0 commit comments