Skip to content

Commit

Permalink
Simplified contextvars usage.
Browse files Browse the repository at this point in the history
Contextvars are unconditionally available since dropping Python 3.6
support in 02fecb6046bb5ec0dbbad00ffcd2043e893fcea5.
  • Loading branch information
goldentroll committed Jan 12, 2023
1 parent 7999067 commit 343ac4b
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 11 deletions.
12 changes: 4 additions & 8 deletions asgiref/sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -395,9 +395,7 @@ async def __call__(self, *args, **kwargs):
if hasattr(AsyncToSync.executors, "current"):
# If we have a parent sync thread above somewhere, use that
executor = AsyncToSync.executors.current
elif self.thread_sensitive_context and self.thread_sensitive_context.get(
None
):
elif self.thread_sensitive_context.get(None):
# If we have a way of retrieving the current context, attempt
# to use a per-context thread pool executor
thread_sensitive_context = self.thread_sensitive_context.get()
Expand All @@ -412,15 +410,14 @@ async def __call__(self, *args, **kwargs):
elif loop in AsyncToSync.loop_thread_executors:
# Re-use thread executor for running loop
executor = AsyncToSync.loop_thread_executors[loop]
elif self.deadlock_context and self.deadlock_context.get(False):
elif self.deadlock_context.get(False):
raise RuntimeError(
"Single thread executor already being used, would deadlock"
)
else:
# Otherwise, we run it in a fixed single thread
executor = self.single_thread_executor
if self.deadlock_context:
self.deadlock_context.set(True)
self.deadlock_context.set(True)
else:
# Use the passed in executor, or the loop's default if it is None
executor = self._executor
Expand Down Expand Up @@ -449,8 +446,7 @@ async def __call__(self, *args, **kwargs):

finally:
_restore_context(context)
if self.deadlock_context:
self.deadlock_context.set(False)
self.deadlock_context.set(False)

return ret

Expand Down
5 changes: 2 additions & 3 deletions tests/test_sync_contextvars.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import asyncio
import contextvars
import threading
import time

import pytest

from asgiref.sync import ThreadSensitiveContext, async_to_sync, sync_to_async

contextvars = pytest.importorskip("contextvars")

foo = contextvars.ContextVar("foo")
foo: "contextvars.ContextVar[str]" = contextvars.ContextVar("foo")


@pytest.mark.asyncio
Expand Down

0 comments on commit 343ac4b

Please sign in to comment.