From 39d10a91d757227352a895615833e59d92f99ed8 Mon Sep 17 00:00:00 2001 From: monosans Date: Fri, 31 May 2024 12:30:10 +0500 Subject: [PATCH] Add async_run function instead of set_event_loop_policy --- nitro_generator_checker/__main__.py | 51 +++++++++++++++-------------- 1 file changed, 26 insertions(+), 25 deletions(-) diff --git a/nitro_generator_checker/__main__.py b/nitro_generator_checker/__main__.py index a35d575..da65dbe 100644 --- a/nitro_generator_checker/__main__.py +++ b/nitro_generator_checker/__main__.py @@ -3,14 +3,14 @@ import asyncio import logging import sys -from typing import TYPE_CHECKING, Dict +from typing import TYPE_CHECKING, Coroutine, Dict import aiofiles import rich.traceback from aiohttp import ClientSession, DummyCookieJar, TCPConnector from rich.console import Console from rich.logging import RichHandler -from typing_extensions import Any +from typing_extensions import Any, TypeVar from . import http from .nitro_checker import NitroChecker @@ -26,31 +26,33 @@ else: import tomli as tomllib +T = TypeVar("T") -def set_event_loop_policy() -> None: + +def async_run(main: Coroutine[Any, Any, T]) -> T: if sys.implementation.name == "cpython": - if sys.platform in {"cygwin", "win32"}: - try: - import winloop # type: ignore[import-not-found] # noqa: PLC0415 - except ImportError: - pass - else: - try: - policy = winloop.EventLoopPolicy() - except AttributeError: - policy = winloop.WinLoopPolicy() - asyncio.set_event_loop_policy(policy) - return - elif sys.platform in {"darwin", "linux"}: - try: - import uvloop # noqa: PLC0415 - except ImportError: - pass - else: - asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) - return + try: + import uvloop # type: ignore[import-not-found, unused-ignore] # noqa: PLC0415 + except ImportError: + pass + else: + if hasattr(uvloop, "run"): + return uvloop.run(main) # type: ignore[no-any-return] + uvloop.install() + return asyncio.run(main) + + try: + import winloop # type: ignore[import-not-found, import-untyped, unused-ignore] # noqa: PLC0415 + except ImportError: + pass + else: + if hasattr(winloop, "run"): + return winloop.run(main) # type: ignore[no-any-return] + winloop.install() + return asyncio.run(main) if sys.platform == "win32": asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) + return asyncio.run(main) async def read_config(file: str, /) -> Dict[str, Any]: @@ -97,5 +99,4 @@ async def main() -> None: if __name__ == "__main__": - set_event_loop_policy() - asyncio.run(main()) + async_run(main())