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
78# pragma: no cover
89class AsyncLock (Protocol ):
910 """A protocol for an asynchronous lock."""
11+
1012 def __init__ (self ) -> None : ...
1113 async def __aenter__ (self ) -> None : ...
1214 async def __aexit__ (self , exc_type , exc_val , exc_tb ) -> None : ...
1315
1416
1517# Define context types as literals
16- AsyncContext = Literal [" asyncio" , " trio" , " unknown" ]
18+ AsyncContext = Literal [' asyncio' , ' trio' , ' unknown' ]
1719
1820
1921# Functions for detecting async context
@@ -60,10 +62,10 @@ def _is_in_trio_context() -> bool:
6062 # Early return if trio is not available
6163 if not has_trio :
6264 return False
63-
65+
6466 # Import trio here since we already checked it's available
6567 import trio
66-
68+
6769 try :
6870 # Will raise RuntimeError if not in trio context
6971 trio .lowlevel .current_task ()
@@ -81,9 +83,9 @@ def detect_async_context() -> AsyncContext:
8183 """
8284 # This branch is only taken when anyio is not installed
8385 if not has_anyio or not _is_in_trio_context ():
84- return " asyncio"
86+ return ' asyncio'
8587
86- return " trio"
88+ return ' trio'
8789
8890
8991_ValueType = TypeVar ('_ValueType' )
@@ -142,7 +144,9 @@ def __init__(self, coro: Awaitable[_ValueType]) -> None:
142144 """We need just an awaitable to work with."""
143145 self ._coro = coro
144146 self ._cache : _ValueType | _Sentinel = _sentinel
145- 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+ )
146150
147151 def __await__ (self ) -> Generator [None , None , _ValueType ]:
148152 """
@@ -192,14 +196,14 @@ def _create_lock(self) -> AsyncLock:
192196 """Create the appropriate lock based on the current async context."""
193197 context = detect_async_context ()
194198
195- if context == " trio" and has_anyio :
199+ if context == ' trio' and has_anyio :
196200 try :
197201 import anyio
198202 except Exception :
199203 # Just continue to asyncio if anyio import fails
200204 return asyncio .Lock ()
201205 return anyio .Lock ()
202-
206+
203207 # For asyncio or unknown contexts
204208 return asyncio .Lock ()
205209
@@ -254,4 +258,4 @@ def decorator(
254258 ) -> _AwaitableT :
255259 return ReAwaitable (coro (* args , ** kwargs )) # type: ignore[return-value]
256260
257- return decorator
261+ return decorator
0 commit comments