1
+ # Always import asyncio
2
+ import asyncio
1
3
from collections .abc import Awaitable , Callable , Generator
2
4
from functools import wraps
3
5
from typing import Literal , NewType , ParamSpec , Protocol , TypeVar , cast , final
4
- # Always import asyncio
5
- import asyncio
6
+
6
7
7
8
class AsyncLock (Protocol ):
8
9
"""A protocol for an asynchronous lock."""
@@ -15,7 +16,7 @@ async def __aexit__(self, exc_type, exc_val, exc_tb) -> None: ...
15
16
16
17
17
18
# Define context types as literals
18
- AsyncContext = Literal [" asyncio" , " trio" , " unknown" ]
19
+ AsyncContext = Literal [' asyncio' , ' trio' , ' unknown' ]
19
20
20
21
21
22
def _is_anyio_available () -> bool : # pragma: no cover
@@ -61,10 +62,10 @@ def _is_in_trio_context() -> bool:
61
62
# Early return if trio is not available
62
63
if not has_trio :
63
64
return False
64
-
65
+
65
66
# Import trio here since we already checked it's available
66
67
import trio
67
-
68
+
68
69
try :
69
70
# Will raise RuntimeError if not in trio context
70
71
trio .lowlevel .current_task ()
@@ -82,9 +83,9 @@ def detect_async_context() -> AsyncContext:
82
83
"""
83
84
# This branch is only taken when anyio is not installed
84
85
if not has_anyio or not _is_in_trio_context (): # pragma: no cover
85
- return " asyncio"
86
+ return ' asyncio'
86
87
87
- return " trio"
88
+ return ' trio'
88
89
89
90
90
91
_ValueType = TypeVar ('_ValueType' )
@@ -143,7 +144,9 @@ def __init__(self, coro: Awaitable[_ValueType]) -> None:
143
144
"""We need just an awaitable to work with."""
144
145
self ._coro = coro
145
146
self ._cache : _ValueType | _Sentinel = _sentinel
146
- self ._lock : AsyncLock | None = None # Will be created lazily based on the backend
147
+ self ._lock : AsyncLock | None = (
148
+ None # Will be created lazily based on the backend
149
+ )
147
150
148
151
def __await__ (self ) -> Generator [None , None , _ValueType ]:
149
152
"""
@@ -193,14 +196,14 @@ def _create_lock(self) -> AsyncLock:
193
196
"""Create the appropriate lock based on the current async context."""
194
197
context = detect_async_context ()
195
198
196
- if context == " trio" and has_anyio : # pragma: no cover
199
+ if context == ' trio' and has_anyio : # pragma: no cover
197
200
try :
198
201
import anyio
199
202
except Exception :
200
203
# Just continue to asyncio if anyio import fails
201
204
return asyncio .Lock ()
202
205
return anyio .Lock ()
203
-
206
+
204
207
# For asyncio or unknown contexts
205
208
return asyncio .Lock ()
206
209
@@ -255,4 +258,4 @@ def decorator(
255
258
) -> _AwaitableT :
256
259
return ReAwaitable (coro (* args , ** kwargs )) # type: ignore[return-value]
257
260
258
- return decorator
261
+ return decorator
0 commit comments