1"""High-level support for working with threads in asyncio"""
2
3import functools
4import contextvars
5
6from . import events
7
8
9__all__ = "to_thread",
10
11
12async def to_thread(func, /, *args, **kwargs):
13    """Asynchronously run function *func* in a separate thread.
14
15    Any *args and **kwargs supplied for this function are directly passed
16    to *func*. Also, the current :class:`contextvars.Context` is propogated,
17    allowing context variables from the main thread to be accessed in the
18    separate thread.
19
20    Return a coroutine that can be awaited to get the eventual result of *func*.
21    """
22    loop = events.get_running_loop()
23    ctx = contextvars.copy_context()
24    func_call = functools.partial(ctx.run, func, *args, **kwargs)
25    return await loop.run_in_executor(None, func_call)
26