Skip to content

Commit 0f12724

Browse files
committed
Fix async context detection and lock creation in reawaitable.py
1 parent c6cea81 commit 0f12724

File tree

1 file changed

+14
-3
lines changed

1 file changed

+14
-3
lines changed

returns/primitives/reawaitable.py

+14-3
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ def _is_in_trio_context() -> bool:
6868
# Will raise RuntimeError if not in trio context
6969
trio.lowlevel.current_task()
7070
except (RuntimeError, AttributeError):
71+
# Not in a trio context or trio API changed
7172
return False
7273
return True
7374

@@ -195,9 +196,13 @@ def _create_lock(self) -> AsyncLock:
195196
context = detect_async_context()
196197

197198
if context == "trio" and has_anyio:
198-
import anyio
199+
try:
200+
import anyio
201+
except Exception:
202+
# Just continue to asyncio if anyio import fails
203+
return asyncio.Lock()
199204
return anyio.Lock()
200-
205+
201206
# For asyncio or unknown contexts
202207
return asyncio.Lock()
203208

@@ -207,7 +212,13 @@ async def _awaitable(self) -> _ValueType:
207212
if self._lock is None:
208213
self._lock = self._create_lock()
209214

210-
async with self._lock:
215+
try:
216+
async with self._lock:
217+
if self._cache is _sentinel:
218+
self._cache = await self._coro
219+
return self._cache # type: ignore
220+
except RuntimeError:
221+
# Fallback for when running in asyncio context with trio detection
211222
if self._cache is _sentinel:
212223
self._cache = await self._coro
213224
return self._cache # type: ignore

0 commit comments

Comments
 (0)