Skip to content

Commit 730d865

Browse files
committed
Simplified contextvars usage.
Contextvars are unconditionally available since dropping Python 3.6 support in 02fecb6.
1 parent 3602263 commit 730d865

File tree

2 files changed

+6
-11
lines changed

2 files changed

+6
-11
lines changed

asgiref/sync.py

+4-8
Original file line numberDiff line numberDiff line change
@@ -395,9 +395,7 @@ async def __call__(self, *args, **kwargs):
395395
if hasattr(AsyncToSync.executors, "current"):
396396
# If we have a parent sync thread above somewhere, use that
397397
executor = AsyncToSync.executors.current
398-
elif self.thread_sensitive_context and self.thread_sensitive_context.get(
399-
None
400-
):
398+
elif self.thread_sensitive_context.get(None):
401399
# If we have a way of retrieving the current context, attempt
402400
# to use a per-context thread pool executor
403401
thread_sensitive_context = self.thread_sensitive_context.get()
@@ -412,15 +410,14 @@ async def __call__(self, *args, **kwargs):
412410
elif loop in AsyncToSync.loop_thread_executors:
413411
# Re-use thread executor for running loop
414412
executor = AsyncToSync.loop_thread_executors[loop]
415-
elif self.deadlock_context and self.deadlock_context.get(False):
413+
elif self.deadlock_context.get(False):
416414
raise RuntimeError(
417415
"Single thread executor already being used, would deadlock"
418416
)
419417
else:
420418
# Otherwise, we run it in a fixed single thread
421419
executor = self.single_thread_executor
422-
if self.deadlock_context:
423-
self.deadlock_context.set(True)
420+
self.deadlock_context.set(True)
424421
else:
425422
# Use the passed in executor, or the loop's default if it is None
426423
executor = self._executor
@@ -449,8 +446,7 @@ async def __call__(self, *args, **kwargs):
449446

450447
finally:
451448
_restore_context(context)
452-
if self.deadlock_context:
453-
self.deadlock_context.set(False)
449+
self.deadlock_context.set(False)
454450

455451
return ret
456452

tests/test_sync_contextvars.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,13 @@
11
import asyncio
2+
import contextvars
23
import threading
34
import time
45

56
import pytest
67

78
from asgiref.sync import ThreadSensitiveContext, async_to_sync, sync_to_async
89

9-
contextvars = pytest.importorskip("contextvars")
10-
11-
foo = contextvars.ContextVar("foo")
10+
foo: "contextvars.ContextVar[str]" = contextvars.ContextVar("foo")
1211

1312

1413
@pytest.mark.asyncio

0 commit comments

Comments
 (0)