From 168324fefc060c9b67cc0f8d1864e4dfcfdcd611 Mon Sep 17 00:00:00 2001 From: Dos Moonen Date: Wed, 17 Jan 2024 16:03:14 +0100 Subject: [PATCH] Take advantage of having dropped Python 3.7 --- aio_pika/__init__.py | 8 ++----- aio_pika/abc.py | 9 +------- aio_pika/queue.py | 52 +++++++++++++++++--------------------------- aio_pika/tools.py | 29 +++++++----------------- docs/source/conf.py | 8 ++----- poetry.lock | 2 +- pyproject.toml | 1 - 7 files changed, 34 insertions(+), 75 deletions(-) diff --git a/aio_pika/__init__.py b/aio_pika/__init__.py index 516eb51e..e18002a4 100644 --- a/aio_pika/__init__.py +++ b/aio_pika/__init__.py @@ -13,12 +13,8 @@ from .robust_queue import RobustQueue -try: - from importlib.metadata import Distribution - __version__ = Distribution.from_name("aio-pika").version -except ImportError: - import pkg_resources - __version__ = pkg_resources.get_distribution("aio-pika").version +from importlib.metadata import Distribution +__version__ = Distribution.from_name("aio-pika").version __all__ = ( diff --git a/aio_pika/abc.py b/aio_pika/abc.py index c8df3214..3e52c8f2 100644 --- a/aio_pika/abc.py +++ b/aio_pika/abc.py @@ -1,6 +1,5 @@ import asyncio import dataclasses -import sys from abc import ABC, abstractmethod from dataclasses import dataclass from datetime import datetime, timedelta @@ -10,15 +9,9 @@ from typing import ( Any, AsyncContextManager, AsyncIterable, Awaitable, Callable, Dict, Generator, Iterator, Mapping, Optional, Tuple, Type, TypeVar, Union, - overload, + overload, Literal, TypedDict, ) - -if sys.version_info >= (3, 8): - from typing import Literal, TypedDict -else: - from typing_extensions import Literal, TypedDict - import aiormq.abc from aiormq.abc import ExceptionType from pamqp.common import Arguments, FieldValue diff --git a/aio_pika/queue.py b/aio_pika/queue.py index 9f9eae4e..5a351109 100644 --- a/aio_pika/queue.py +++ b/aio_pika/queue.py @@ -1,8 +1,8 @@ import asyncio -import sys from functools import partial from types import TracebackType -from typing import Any, Awaitable, Callable, Optional, Type, overload +from typing import Any, Awaitable, Callable, Optional, Type, overload, Literal, \ + Set import aiormq from aiormq.abc import DeliveredMessage @@ -19,12 +19,6 @@ from .tools import CallbackCollection, create_task, ensure_awaitable -if sys.version_info >= (3, 8): - from typing import Literal -else: - from typing_extensions import Literal - - log = get_logger(__name__) @@ -553,39 +547,26 @@ async def __anext__(self) -> IncomingMessage: ) timeout = self._consume_kwargs.get("timeout") - sleep = asyncio.get_running_loop().create_future() - - if timeout is not None: - sleep = asyncio.create_task( - asyncio.sleep(timeout), - name=f"waiting for {self} to timeout after {timeout} seconds" - ) - else: - timeout = self.DEFAULT_CLOSE_TIMEOUT - pending = {message, closed_channel, closed, sleep} + done: Set[asyncio.Task] = set() + pending = {message, closed_channel, closed} try: done, pending = await asyncio.wait( - pending, return_when=asyncio.FIRST_COMPLETED + pending, return_when=asyncio.FIRST_COMPLETED, timeout=timeout ) + cancelled = False except asyncio.CancelledError: - # Increase coverage score - pass - finally: - for task in pending: - task.cancel() + cancelled = True - await asyncio.wait(pending) + for task in pending: + task.cancel() - if not message.cancelled(): - return message.result() - - if not closed.cancelled() or not closed_channel.cancelled(): - self._closed.set() - raise StopAsyncIteration + await asyncio.wait(pending) - if not sleep.cancelled(): + if not done and not cancelled: + if timeout is None: + timeout = self.DEFAULT_CLOSE_TIMEOUT log.info( "%r closing with timeout %d seconds", self, timeout, @@ -593,6 +574,13 @@ async def __anext__(self) -> IncomingMessage: await asyncio.wait_for(self.close(), timeout=timeout) raise TimeoutError + if not message.cancelled(): + return message.result() + + if not closed.cancelled() or not closed_channel.cancelled(): + self._closed.set() + raise StopAsyncIteration + raise asyncio.CancelledError diff --git a/aio_pika/tools.py b/aio_pika/tools.py index daec83ea..890a794b 100644 --- a/aio_pika/tools.py +++ b/aio_pika/tools.py @@ -19,25 +19,12 @@ def iscoroutinepartial(fn: Callable[..., Any]) -> bool: """ - Function returns True if function is a partial instance of coroutine. - See additional information here_. - - :param fn: Function - :return: bool - - .. _here: https://goo.gl/C0S4sQ - + Use Python 3.8's inspect.iscoroutinefunction() instead """ - - while True: - parent = fn - - fn = getattr(parent, "func", None) # type: ignore - - if fn is None: - break - - return asyncio.iscoroutinefunction(parent) + warnings.warn( + "Use inspect.iscoroutinefunction() instead.", DeprecationWarning + ) + return asyncio.iscoroutinefunction(fn) def _task_done(future: asyncio.Future) -> None: @@ -57,8 +44,8 @@ def create_task( ) -> Awaitable[T]: loop = loop or asyncio.get_event_loop() - if iscoroutinepartial(func): - task = loop.create_task(func(*args, **kwargs)) # type: ignore + if inspect.iscoroutinefunction(func): + task = loop.create_task(func(*args, **kwargs)) task.add_done_callback(_task_done) return task @@ -260,7 +247,7 @@ def ensure_awaitable( if inspect.iscoroutinefunction(func): return func - if inspect.isfunction(func) and not iscoroutinepartial(func): + if inspect.isfunction(func): warnings.warn( f"You probably registering the non-coroutine function {func!r}. " "This is deprecated and will be removed in future releases. " diff --git a/docs/source/conf.py b/docs/source/conf.py index 65f57a12..689f897b 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -23,12 +23,8 @@ # noinspection PyUnresolvedReferences -try: - from importlib.metadata import Distribution - __version__ = Distribution.from_name("aio-pika").version -except ImportError: - import pkg_resources - __version__ = pkg_resources.get_distribution("aio-pika").version +from importlib.metadata import Distribution +__version__ = Distribution.from_name("aio-pika").version sys.path.insert(0, os.path.abspath(os.path.dirname("__file__"))) diff --git a/poetry.lock b/poetry.lock index 734277c0..cacb05df 100644 --- a/poetry.lock +++ b/poetry.lock @@ -1442,4 +1442,4 @@ testing = ["big-O", "jaraco.functools", "jaraco.itertools", "more-itertools", "p [metadata] lock-version = "2.0" python-versions = "^3.8" -content-hash = "21f4ae7609bb1ec451db75f51b8ecd7b34bccb8c5f089183a962064baf79bebf" +content-hash = "ab56db67b46cf73e711d90fa7902768e1a6a60dac3e8b7b3957ab4edf973f8b5" diff --git a/pyproject.toml b/pyproject.toml index 2b731393..cc67e38c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -38,7 +38,6 @@ packages = [{ include = "aio_pika" }] python = "^3.8" aiormq = "~6.8.0" yarl = [{ version = '*'}] -typing_extensions = [{ version = '*', python = "< 3.8" }] # for pkg_resources setuptools = [{ version = '*', python = "< 3.8" }]