Skip to content

Instantly share code, notes, and snippets.

@rafalkrupinski
Created May 20, 2025 16:09
Show Gist options
  • Save rafalkrupinski/b0e13baefd45638b66884584e4af397a to your computer and use it in GitHub Desktop.
Save rafalkrupinski/b0e13baefd45638b66884584e4af397a to your computer and use it in GitHub Desktop.
Nicer asyncio.to_thread
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
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