Last active
August 8, 2023 05:58
-
-
Save Guiforge/13b85811750e8a762cc550b74746d175 to your computer and use it in GitHub Desktop.
Synchronous waiting for an asynchronous coroutine with Type
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
from collections.abc import Coroutine | |
from typing import Any, TypeVar | |
T = TypeVar("T") | |
def swait(awaitable: Coroutine[Any, Any, T]) -> T: | |
"""Wait but for in syncronous function. | |
>>> import time | |
>>> import asyncio | |
>>> start = time.time() | |
>>> swait(asyncio.sleep(3)) | |
>>> print(f"{time.time() - start}") | |
3.010016679763794 | |
Args: | |
awaitable (Coroutine[Any, Any, T]): _description_ | |
Returns: | |
T: the result coroutine | |
""" | |
try: | |
loop = asyncio.get_event_loop() | |
return loop.run_until_complete(awaitable) | |
except RuntimeError: | |
# no event loop running | |
return asyncio.run(awaitable) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment