From b147c6229a068dfcf1ce954e86b775be7ad6f520 Mon Sep 17 00:00:00 2001 From: Caleb Hattingh Date: Mon, 27 Jan 2025 12:56:54 +0100 Subject: [PATCH] Refactor module to package and incl py.typed. Fix #93 (#94) * Refactor module to package and incl py.typed * Include type for the weakset * Assist mypy to notice that `loop` loses `Optional` * Ignore a mypy error about a private attribute access * Try AbstractSet type sig for Python 3.8 --- aiorun.py => aiorun/__init__.py | 12 ++++++++---- aiorun/py.typed | 0 2 files changed, 8 insertions(+), 4 deletions(-) rename aiorun.py => aiorun/__init__.py (97%) create mode 100644 aiorun/py.typed diff --git a/aiorun.py b/aiorun/__init__.py similarity index 97% rename from aiorun.py rename to aiorun/__init__.py index 06beb02..fa2df40 100644 --- a/aiorun.py +++ b/aiorun/__init__.py @@ -8,7 +8,7 @@ from asyncio import AbstractEventLoop, CancelledError, all_tasks, get_event_loop from concurrent.futures import Executor, ThreadPoolExecutor from functools import partial -from typing import Awaitable, Callable, Coroutine, Optional, Union +from typing import Awaitable, Callable, Coroutine, Optional, Union, AbstractSet from weakref import WeakSet ShutdownCallback = Optional[ @@ -26,7 +26,8 @@ WINDOWS = sys.platform == "win32" -_DO_NOT_CANCEL_COROS = WeakSet() +# TODO: when 3.8 is dropped, replace `AbstractSet` with `WeakSet` +_DO_NOT_CANCEL_COROS: AbstractSet[Coroutine] = WeakSet() def shutdown_waits_for(coro, loop=None): @@ -170,7 +171,10 @@ def run( loop_was_supplied = bool(loop) - if not loop_was_supplied: + # If we check `loop_was_supplied` here, mypy will forever complain + # that `loop` might be None. So we have to check loop directly here + # to silence these incorrect mypy complaints. Yay for typing. + if not loop: if use_uvloop: import uvloop @@ -293,7 +297,7 @@ async def new_coro(): for t in tasks: # TODO: we don't need access to the coro. We could simply # TODO: store the task itself in the weakset. - if t._coro not in _DO_NOT_CANCEL_COROS: + if t._coro not in _DO_NOT_CANCEL_COROS: # type: ignore t.cancel() async def wait_for_cancelled_tasks(timeout): diff --git a/aiorun/py.typed b/aiorun/py.typed new file mode 100644 index 0000000..e69de29