Take a blocking function and create an async one that receives the same positional and keyword arguments. For python version 3.9 and above, it uses asyncio.to_thread to run the function in a separate thread. For python version 3.8, it uses locally defined copy of the asyncio.to_thre
(function: Callable[T_ParamSpec, T_Retval])
| 51 | |
| 52 | # inspired by `asyncer`, https://github.com/tiangolo/asyncer |
| 53 | def asyncify(function: Callable[T_ParamSpec, T_Retval]) -> Callable[T_ParamSpec, Awaitable[T_Retval]]: |
| 54 | """ |
| 55 | Take a blocking function and create an async one that receives the same |
| 56 | positional and keyword arguments. For python version 3.9 and above, it uses |
| 57 | asyncio.to_thread to run the function in a separate thread. For python version |
| 58 | 3.8, it uses locally defined copy of the asyncio.to_thread function which was |
| 59 | introduced in python 3.9. |
| 60 | |
| 61 | Usage: |
| 62 | |
| 63 | ```python |
| 64 | def blocking_func(arg1, arg2, kwarg1=None): |
| 65 | # blocking code |
| 66 | return result |
| 67 | |
| 68 | |
| 69 | result = asyncify(blocking_function)(arg1, arg2, kwarg1=value1) |
| 70 | ``` |
| 71 | |
| 72 | ## Arguments |
| 73 | |
| 74 | `function`: a blocking regular callable (e.g. a function) |
| 75 | |
| 76 | ## Return |
| 77 | |
| 78 | An async function that takes the same positional and keyword arguments as the |
| 79 | original one, that when called runs the same original function in a thread worker |
| 80 | and returns the result. |
| 81 | """ |
| 82 | |
| 83 | async def wrapper(*args: T_ParamSpec.args, **kwargs: T_ParamSpec.kwargs) -> T_Retval: |
| 84 | return await to_thread(function, *args, **kwargs) |
| 85 | |
| 86 | return wrapper |