Skip to content

Instantly share code, notes, and snippets.

@Guiforge
Last active August 8, 2023 05:58
Show Gist options
  • Save Guiforge/13b85811750e8a762cc550b74746d175 to your computer and use it in GitHub Desktop.
Save Guiforge/13b85811750e8a762cc550b74746d175 to your computer and use it in GitHub Desktop.
Synchronous waiting for an asynchronous coroutine with Type
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