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 :
@@ -60,10 +61,10 @@ def _is_in_trio_context() -> bool:
6061 """
6162 if not has_trio :
6263 return False # pragma: no cover
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 ()
@@ -80,13 +81,13 @@ def detect_async_context() -> AsyncContext:
8081 AsyncContext: The current async context type
8182 """
8283 if not has_anyio : # pragma: no cover
83- return " asyncio"
84+ return ' asyncio'
8485
8586 if _is_in_trio_context ():
86- return " trio"
87+ return ' trio'
8788
8889 # Default to asyncio
89- return " asyncio"
90+ return ' asyncio'
9091
9192
9293_ValueType = TypeVar ('_ValueType' )
@@ -145,7 +146,9 @@ def __init__(self, coro: Awaitable[_ValueType]) -> None:
145146 """We need just an awaitable to work with."""
146147 self ._coro = coro
147148 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+ )
149152
150153 def __await__ (self ) -> Generator [None , None , _ValueType ]:
151154 """
@@ -195,14 +198,14 @@ def _create_lock(self) -> AsyncLock:
195198 """Create the appropriate lock based on the current async context."""
196199 context = detect_async_context ()
197200
198- if context == " trio" and has_anyio :
201+ if context == ' trio' and has_anyio :
199202 try :
200203 import anyio
201204 except Exception : # pragma: no cover
202205 # Just continue to asyncio if anyio import fails
203206 return asyncio .Lock () # pragma: no cover
204207 return anyio .Lock () # pragma: no cover
205-
208+
206209 # For asyncio or unknown contexts
207210 return asyncio .Lock ()
208211
@@ -222,6 +225,8 @@ async def _awaitable(self) -> _ValueType:
222225 if self ._cache is _sentinel :
223226 self ._cache = await self ._coro
224227 return self ._cache # type: ignore
228+
229+
225230# pragma: no cover
226231
227232
@@ -258,4 +263,4 @@ def decorator(
258263 ) -> _AwaitableT :
259264 return ReAwaitable (coro (* args , ** kwargs )) # type: ignore[return-value]
260265
261- return decorator
266+ return decorator
0 commit comments