File tree Expand file tree Collapse file tree 2 files changed +23
-1
lines changed Expand file tree Collapse file tree 2 files changed +23
-1
lines changed Original file line number Diff line number Diff line change 11import array
22import asyncio
3+ import contextvars
34import functools
45import io
56import os
@@ -554,6 +555,22 @@ async def test_offload():
554555 assert (await offload (lambda x , y : x + y , 1 , y = 2 )) == 3
555556
556557
558+ @pytest .mark .asyncio
559+ async def test_offload_preserves_contextvars ():
560+ var = contextvars .ContextVar ("var" , default = "foo" )
561+
562+ def change_var ():
563+ var .set ("bar" )
564+ return var .get ()
565+
566+ o1 = offload (var .get )
567+ o2 = offload (change_var )
568+
569+ r1 , r2 = await asyncio .gather (o1 , o2 )
570+ assert (r1 , r2 ) == ("foo" , "bar" )
571+ assert var .get () == "foo"
572+
573+
557574def test_serialize_for_cli_deprecated ():
558575 with pytest .warns (FutureWarning , match = "serialize_for_cli is deprecated" ):
559576 from distributed .utils import serialize_for_cli
Original file line number Diff line number Diff line change 11from __future__ import annotations
22
33import asyncio
4+ import contextvars
45import functools
56import importlib
67import inspect
@@ -1322,7 +1323,11 @@ def import_term(name: str):
13221323
13231324async def offload (fn , * args , ** kwargs ):
13241325 loop = asyncio .get_event_loop ()
1325- return await loop .run_in_executor (_offload_executor , lambda : fn (* args , ** kwargs ))
1326+ # Retain context vars while deserializing; see https://bugs.python.org/issue34014
1327+ context = contextvars .copy_context ()
1328+ return await loop .run_in_executor (
1329+ _offload_executor , lambda : context .run (fn , * args , ** kwargs )
1330+ )
13261331
13271332
13281333class EmptyContext :
You can’t perform that action at this time.
0 commit comments