@@ -94,7 +94,8 @@ def sync_to_async(
94
94
return _sync_to_async_non_bridge (coro , args , kwargs )
95
95
96
96
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 ()
98
99
event = _ThreadPool .get (loop ).all [threading .current_thread ()].event
99
100
100
101
event .clear ()
@@ -104,7 +105,7 @@ def do_it():
104
105
nonlocal task , inner_exception
105
106
logger .debug ("Creating task in %s from %s" , loop , thread_name := threading .current_thread ().name )
106
107
try :
107
- task = loop .create_task (coro , context = context . copy () )
108
+ task = loop .create_task (coro , context = sync_thread_context_copy )
108
109
except Exception as exc :
109
110
# abort if there is an error creating the task itself!
110
111
event .set ()
@@ -220,7 +221,7 @@ def _sync_worker(queue):
220
221
loop = sync_task_bundle .loop
221
222
fut = sync_task_bundle .done_future
222
223
try :
223
- result = context .run (_in_context_sync_worker , sync_task_bundle )
224
+ result = context .copy (). run (_in_context_sync_worker , sync_task_bundle )
224
225
except BaseException as exc :
225
226
result = exc
226
227
loop .call_soon_threadsafe (fut .set_exception , result )
@@ -260,7 +261,9 @@ def async_to_sync(
260
261
261
262
task = asyncio .current_task ()
262
263
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
264
267
265
268
done_future = loop .create_future ()
266
269
0 commit comments