Skip to content

Commit bf85bef

Browse files
committed
ContextVars tests, More sanity in contexts passing
1 parent a1d6e59 commit bf85bef

File tree

2 files changed

+8
-4
lines changed

2 files changed

+8
-4
lines changed

extraasync/sync_async_bridge.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,8 @@ def sync_to_async(
9494
return _sync_to_async_non_bridge(coro, args, kwargs)
9595

9696
loop = root_sync_task.loop
97-
context = root_sync_task.context
97+
# context = root_sync_task.context
98+
sync_thread_context_copy = contextvars.copy_context()
9899
event = _ThreadPool.get(loop).all[threading.current_thread()].event
99100

100101
event.clear()
@@ -104,7 +105,7 @@ def do_it():
104105
nonlocal task, inner_exception
105106
logger.debug("Creating task in %s from %s", loop, thread_name:=threading.current_thread().name)
106107
try:
107-
task = loop.create_task(coro, context=context.copy())
108+
task = loop.create_task(coro, context=sync_thread_context_copy)
108109
except Exception as exc:
109110
# abort if there is an error creating the task itself!
110111
event.set()
@@ -220,7 +221,7 @@ def _sync_worker(queue):
220221
loop = sync_task_bundle.loop
221222
fut = sync_task_bundle.done_future
222223
try:
223-
result = context.run(_in_context_sync_worker, sync_task_bundle)
224+
result = context.copy().run(_in_context_sync_worker, sync_task_bundle)
224225
except BaseException as exc:
225226
result = exc
226227
loop.call_soon_threadsafe(fut.set_exception, result)
@@ -260,7 +261,9 @@ def async_to_sync(
260261

261262
task = asyncio.current_task()
262263
loop = task.get_loop()
263-
context = task.get_context().copy()
264+
context = task.get_context() # it is resposibility of those using the context to copy it!
265+
# (also, with the "extracontext" package, there are
266+
# tools to modify an existing context if needed
264267

265268
done_future = loop.create_future()
266269

tests/test_async_sync_bridge.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -390,6 +390,7 @@ async def async_end(value):
390390
return (value, context_test.get())
391391

392392
def sync_step(value):
393+
393394
# This is what we are testing here:
394395
# sync call, in other thread, sets context value visible back on async task!
395396
context_test.set(value)

0 commit comments

Comments
 (0)