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
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 ()
@@ -79,13 +80,13 @@ def detect_async_context() -> AsyncContext:
7980 AsyncContext: The current async context type
8081 """
8182 if not has_anyio : # pragma: no cover
82- return " asyncio"
83+ return ' asyncio'
8384
8485 if _is_in_trio_context ():
85- return " trio"
86+ return ' trio'
8687
8788 # Default to asyncio
88- return " asyncio"
89+ return ' asyncio'
8990
9091
9192_ValueType = TypeVar ('_ValueType' )
@@ -144,7 +145,9 @@ def __init__(self, coro: Awaitable[_ValueType]) -> None:
144145 """We need just an awaitable to work with."""
145146 self ._coro = coro
146147 self ._cache : _ValueType | _Sentinel = _sentinel
147- self ._lock : AsyncLock | None = None # Will be created lazily based on the backend
148+ self ._lock : AsyncLock | None = (
149+ None # Will be created lazily based on the backend
150+ )
148151
149152 def __await__ (self ) -> Generator [None , None , _ValueType ]:
150153 """
@@ -194,8 +197,9 @@ def _create_lock(self) -> AsyncLock:
194197 """Create the appropriate lock based on the current async context."""
195198 context = detect_async_context ()
196199
197- if context == " trio" and has_anyio :
200+ if context == ' trio' and has_anyio :
198201 import anyio
202+
199203 return anyio .Lock ()
200204
201205 # For asyncio or unknown contexts
@@ -246,4 +250,4 @@ def decorator(
246250 ) -> _AwaitableT :
247251 return ReAwaitable (coro (* args , ** kwargs )) # type: ignore[return-value]
248252
249- return decorator
253+ return decorator
0 commit comments