Coverage for Lib/asyncio/threads.py: 100%

9 statements  

« prev     ^ index     » next       coverage.py v7.14.3, created at 2026-06-24 03:28 +0000

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 propagated, 

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 

21 *func*. 

22 """ 

23 loop = events.get_running_loop() 

24 ctx = contextvars.copy_context() 

25 func_call = functools.partial(ctx.run, func, *args, **kwargs) 

26 return await loop.run_in_executor(None, func_call)