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
@@ -60,10 +61,10 @@ def _is_in_trio_context() -> bool:
60
61
"""
61
62
if not has_trio : # pragma: no cover
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 ()
@@ -81,9 +82,9 @@ def detect_async_context() -> AsyncContext:
81
82
"""
82
83
# This branch is only taken when anyio is not installed
83
84
if not has_anyio or not _is_in_trio_context (): # pragma: no cover
84
- return " asyncio"
85
+ return ' asyncio'
85
86
86
- return " trio"
87
+ return ' trio'
87
88
88
89
89
90
_ValueType = TypeVar ('_ValueType' )
@@ -142,7 +143,9 @@ def __init__(self, coro: Awaitable[_ValueType]) -> None:
142
143
"""We need just an awaitable to work with."""
143
144
self ._coro = coro
144
145
self ._cache : _ValueType | _Sentinel = _sentinel
145
- self ._lock : AsyncLock | None = None # Will be created lazily based on the backend
146
+ self ._lock : AsyncLock | None = (
147
+ None # Will be created lazily based on the backend
148
+ )
146
149
147
150
def __await__ (self ) -> Generator [None , None , _ValueType ]:
148
151
"""
@@ -192,14 +195,14 @@ def _create_lock(self) -> AsyncLock:
192
195
"""Create the appropriate lock based on the current async context."""
193
196
context = detect_async_context ()
194
197
195
- if context == " trio" and has_anyio : # pragma: no cover
198
+ if context == ' trio' and has_anyio : # pragma: no cover
196
199
try :
197
200
import anyio
198
201
except Exception :
199
202
# Just continue to asyncio if anyio import fails
200
203
return asyncio .Lock ()
201
204
return anyio .Lock ()
202
-
205
+
203
206
# For asyncio or unknown contexts
204
207
return asyncio .Lock ()
205
208
@@ -254,4 +257,4 @@ def decorator(
254
257
) -> _AwaitableT :
255
258
return ReAwaitable (coro (* args , ** kwargs )) # type: ignore[return-value]
256
259
257
- return decorator
260
+ return decorator
0 commit comments