Skip to content

Commit 278ad10

Browse files
committed
Use task as state whenever possible.
1 parent 9b23258 commit 278ad10

File tree

1 file changed

+14
-3
lines changed

1 file changed

+14
-3
lines changed

contextvars/__init__.py

+14-3
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import asyncio
12
import collections.abc
23
import threading
34

@@ -186,15 +187,25 @@ def copy_context():
186187

187188

188189
def _get_context():
189-
ctx = getattr(_state, 'context', None)
190+
state = _get_state()
191+
ctx = getattr(state, 'context', None)
190192
if ctx is None:
191193
ctx = Context()
192-
_state.context = ctx
194+
state.context = ctx
193195
return ctx
194196

195197

196198
def _set_context(ctx):
197-
_state.context = ctx
199+
state = _get_state()
200+
state.context = ctx
201+
202+
203+
def _get_state():
204+
loop = asyncio._get_running_loop()
205+
if loop is None:
206+
return _state
207+
task = asyncio.Task.current_task(loop=loop)
208+
return _state if task is None else task
198209

199210

200211
_state = threading.local()

0 commit comments

Comments
 (0)