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 :
@@ -60,10 +61,10 @@ def _is_in_trio_context() -> bool:
60
61
"""
61
62
if not has_trio :
62
63
return False
63
-
64
+
64
65
# Import trio here since we already checked it's available
65
66
import trio
66
-
67
+
67
68
try :
68
69
# Will raise RuntimeError if not in trio context
69
70
trio .lowlevel .current_task ()
@@ -79,13 +80,13 @@ def detect_async_context() -> AsyncContext:
79
80
AsyncContext: The current async context type
80
81
"""
81
82
if not has_anyio : # pragma: no cover
82
- return " asyncio"
83
+ return ' asyncio'
83
84
84
85
if _is_in_trio_context ():
85
- return " trio"
86
+ return ' trio'
86
87
87
88
# Default to asyncio
88
- return " asyncio"
89
+ return ' asyncio'
89
90
90
91
91
92
_ValueType = TypeVar ('_ValueType' )
@@ -144,7 +145,9 @@ def __init__(self, coro: Awaitable[_ValueType]) -> None:
144
145
"""We need just an awaitable to work with."""
145
146
self ._coro = coro
146
147
self ._cache : _ValueType | _Sentinel = _sentinel
147
- self ._lock : AsyncLock | None = None # Will be created lazily based on the backend
148
+ self ._lock : AsyncLock | None = (
149
+ None # Will be created lazily based on the backend
150
+ )
148
151
149
152
def __await__ (self ) -> Generator [None , None , _ValueType ]:
150
153
"""
@@ -194,8 +197,9 @@ def _create_lock(self) -> AsyncLock:
194
197
"""Create the appropriate lock based on the current async context."""
195
198
context = detect_async_context ()
196
199
197
- if context == " trio" and has_anyio :
200
+ if context == ' trio' and has_anyio :
198
201
import anyio
202
+
199
203
return anyio .Lock ()
200
204
201
205
# For asyncio or unknown contexts
@@ -246,4 +250,4 @@ def decorator(
246
250
) -> _AwaitableT :
247
251
return ReAwaitable (coro (* args , ** kwargs )) # type: ignore[return-value]
248
252
249
- return decorator
253
+ return decorator
0 commit comments