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
@@ -60,10 +61,10 @@ def _is_in_trio_context() -> bool:
6061 """
6162 if not has_trio : # pragma: no cover
6263 return False
63-
64+
6465 # Import trio here since we already checked it's available
6566 import trio
66-
67+
6768 try :
6869 # Will raise RuntimeError if not in trio context
6970 trio .lowlevel .current_task ()
@@ -81,9 +82,9 @@ def detect_async_context() -> AsyncContext:
8182 """
8283 # This branch is only taken when anyio is not installed
8384 if not has_anyio or not _is_in_trio_context (): # pragma: no cover
84- return " asyncio"
85+ return ' asyncio'
8586
86- return " trio"
87+ return ' trio'
8788
8889
8990_ValueType = TypeVar ('_ValueType' )
@@ -142,7 +143,9 @@ def __init__(self, coro: Awaitable[_ValueType]) -> None:
142143 """We need just an awaitable to work with."""
143144 self ._coro = coro
144145 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+ )
146149
147150 def __await__ (self ) -> Generator [None , None , _ValueType ]:
148151 """
@@ -192,14 +195,14 @@ def _create_lock(self) -> AsyncLock:
192195 """Create the appropriate lock based on the current async context."""
193196 context = detect_async_context ()
194197
195- if context == " trio" and has_anyio : # pragma: no cover
198+ if context == ' trio' and has_anyio : # pragma: no cover
196199 try :
197200 import anyio
198201 except Exception :
199202 # Just continue to asyncio if anyio import fails
200203 return asyncio .Lock ()
201204 return anyio .Lock ()
202-
205+
203206 # For asyncio or unknown contexts
204207 return asyncio .Lock ()
205208
@@ -254,4 +257,4 @@ def decorator(
254257 ) -> _AwaitableT :
255258 return ReAwaitable (coro (* args , ** kwargs )) # type: ignore[return-value]
256259
257- return decorator
260+ return decorator
0 commit comments