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

9 statements  

« prev     ^ index     » next       coverage.py v7.8.0, created at 2025-04-15 02:02 +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 *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)