Created
June 28, 2023 08:42
-
-
Save Wauplin/6b03f4d43c01f8d489bd1b0495a55a8f to your computer and use it in GitHub Desktop.
Test syncify-like decorator to define both a Sync and Async client
This file contains hidden or 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 | |
import functools | |
from typing import Callable, Coroutine, Any, TypeVar, ParamSpec | |
T_Retval = TypeVar("T_Retval") | |
T_ParamSpec = ParamSpec("T_ParamSpec") | |
def syncify(async_function: Callable[T_ParamSpec, Coroutine[Any, Any, T_Retval]]) -> Callable[T_ParamSpec, T_Retval]: | |
# Taken from https://github.com/tiangolo/asyncer and simplified | |
@functools.wraps(async_function) | |
def wrapper(*args: T_ParamSpec.args, **kwargs: T_ParamSpec.kwargs) -> T_Retval: | |
loop = asyncio.new_event_loop() | |
return loop.run_until_complete(async_function(*args, **kwargs)) | |
return wrapper | |
class AsyncClient: | |
async def say_hello(self, name: str = "hf") -> str: | |
"""Say hello.""" | |
return f"Hello {name}!" | |
class Client: | |
say_hello = syncify(AsyncClient.say_hello) | |
client = Client() | |
print(client.say_hello("world")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment