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
# pragma: no cover
@@ -63,10 +64,10 @@ def _is_in_trio_context() -> bool:
63
64
# Early return if trio is not available
64
65
if not has_trio :
65
66
return False
66
-
67
+
67
68
# Import trio here since we already checked it's available
68
69
import trio
69
-
70
+
70
71
try :
71
72
# Will raise RuntimeError if not in trio context
72
73
trio .lowlevel .current_task ()
@@ -84,9 +85,9 @@ def detect_async_context() -> AsyncContext:
84
85
"""
85
86
# This branch is only taken when anyio is not installed
86
87
if not has_anyio or not _is_in_trio_context ():
87
- return " asyncio"
88
+ return ' asyncio'
88
89
89
- return " trio"
90
+ return ' trio'
90
91
91
92
92
93
_ValueType = TypeVar ('_ValueType' )
@@ -145,7 +146,9 @@ def __init__(self, coro: Awaitable[_ValueType]) -> None:
145
146
"""We need just an awaitable to work with."""
146
147
self ._coro = coro
147
148
self ._cache : _ValueType | _Sentinel = _sentinel
148
- self ._lock : AsyncLock | None = None # Will be created lazily based on the backend
149
+ self ._lock : AsyncLock | None = (
150
+ None # Will be created lazily based on the backend
151
+ )
149
152
150
153
def __await__ (self ) -> Generator [None , None , _ValueType ]:
151
154
"""
@@ -195,14 +198,14 @@ def _create_lock(self) -> AsyncLock:
195
198
"""Create the appropriate lock based on the current async context."""
196
199
context = detect_async_context ()
197
200
198
- if context == " trio" and has_anyio :
201
+ if context == ' trio' and has_anyio :
199
202
try :
200
203
import anyio
201
204
except Exception :
202
205
# Just continue to asyncio if anyio import fails
203
206
return asyncio .Lock ()
204
207
return anyio .Lock ()
205
-
208
+
206
209
# For asyncio or unknown contexts
207
210
return asyncio .Lock ()
208
211
@@ -257,4 +260,4 @@ def decorator(
257
260
) -> _AwaitableT :
258
261
return ReAwaitable (coro (* args , ** kwargs )) # type: ignore[return-value]
259
262
260
- return decorator
263
+ return decorator
0 commit comments