1+ # Always import asyncio
2+ import asyncio
13from collections .abc import Awaitable , Callable , Generator
24from functools import wraps
35from typing import Literal , NewType , ParamSpec , Protocol , TypeVar , cast , final
4- # Always import asyncio
5- import asyncio
6+
67
78class AsyncLock (Protocol ):
89 """A protocol for an asynchronous lock."""
@@ -15,7 +16,7 @@ async def __aexit__(self, exc_type, exc_val, exc_tb) -> None: ...
1516
1617
1718# Define context types as literals
18- AsyncContext = Literal [" asyncio" , " trio" , " unknown" ]
19+ AsyncContext = Literal [' asyncio' , ' trio' , ' unknown' ]
1920
2021
2122def _is_anyio_available () -> bool : # pragma: no cover
@@ -61,10 +62,10 @@ def _is_in_trio_context() -> bool:
6162 # Early return if trio is not available
6263 if not has_trio :
6364 return False
64-
65+
6566 # Import trio here since we already checked it's available
6667 import trio
67-
68+
6869 try :
6970 # Will raise RuntimeError if not in trio context
7071 trio .lowlevel .current_task ()
@@ -82,9 +83,9 @@ def detect_async_context() -> AsyncContext:
8283 """
8384 # This branch is only taken when anyio is not installed
8485 if not has_anyio or not _is_in_trio_context (): # pragma: no cover
85- return " asyncio"
86+ return ' asyncio'
8687
87- return " trio"
88+ return ' trio'
8889
8990
9091_ValueType = TypeVar ('_ValueType' )
@@ -143,7 +144,9 @@ def __init__(self, coro: Awaitable[_ValueType]) -> None:
143144 """We need just an awaitable to work with."""
144145 self ._coro = coro
145146 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+ )
147150
148151 def __await__ (self ) -> Generator [None , None , _ValueType ]:
149152 """
@@ -193,14 +196,14 @@ def _create_lock(self) -> AsyncLock:
193196 """Create the appropriate lock based on the current async context."""
194197 context = detect_async_context ()
195198
196- if context == " trio" and has_anyio : # pragma: no cover
199+ if context == ' trio' and has_anyio : # pragma: no cover
197200 try :
198201 import anyio
199202 except Exception :
200203 # Just continue to asyncio if anyio import fails
201204 return asyncio .Lock ()
202205 return anyio .Lock ()
203-
206+
204207 # For asyncio or unknown contexts
205208 return asyncio .Lock ()
206209
@@ -255,4 +258,4 @@ def decorator(
255258 ) -> _AwaitableT :
256259 return ReAwaitable (coro (* args , ** kwargs )) # type: ignore[return-value]
257260
258- return decorator
261+ return decorator
0 commit comments