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