Created
May 20, 2025 16:09
-
-
Save rafalkrupinski/b0e13baefd45638b66884584e4af397a to your computer and use it in GitHub Desktop.
Nicer asyncio.to_thread
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
from typing import ParamSpec, TypeVar | |
from collections.abc import Callable, Coroutine | |
import functools | |
P = ParamSpec('P') | |
R = TypeVar('R') | |
def to_thread2(fn: Callable[P, R]) -> Callable[P, Coroutine[Any, Any, R]]: | |
functools.wraps(fn) | |
async def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: | |
return await asyncio.to_thread(fn, *args, **kwargs) | |
return wrapper |
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
def a(a: str) -> str: | |
return a+" in thread" | |
async def x(): | |
x = to_thread2(a) | |
await x('b') | |
await to_thread2(a)('b') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment