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# pragma: no cover
@@ -62,10 +64,10 @@ def _is_in_trio_context() -> bool:
6264 # Early return if trio is not available
6365 if not has_trio :
6466 return False
65-
67+
6668 # Import trio here since we already checked it's available
6769 import trio
68-
70+
6971 try :
7072 # Will raise RuntimeError if not in trio context
7173 trio .lowlevel .current_task ()
@@ -83,9 +85,9 @@ def detect_async_context() -> AsyncContext:
8385 """
8486 # This branch is only taken when anyio is not installed
8587 if not has_anyio or not _is_in_trio_context ():
86- return " asyncio"
88+ return ' asyncio'
8789
88- return " trio"
90+ return ' trio'
8991
9092
9193_ValueType = TypeVar ('_ValueType' )
@@ -144,7 +146,9 @@ def __init__(self, coro: Awaitable[_ValueType]) -> None:
144146 """We need just an awaitable to work with."""
145147 self ._coro = coro
146148 self ._cache : _ValueType | _Sentinel = _sentinel
147- 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+ )
148152
149153 def __await__ (self ) -> Generator [None , None , _ValueType ]:
150154 """
@@ -194,14 +198,14 @@ def _create_lock(self) -> AsyncLock:
194198 """Create the appropriate lock based on the current async context."""
195199 context = detect_async_context ()
196200
197- if context == " trio" and has_anyio :
201+ if context == ' trio' and has_anyio :
198202 try :
199203 import anyio
200204 except Exception :
201205 # Just continue to asyncio if anyio import fails
202206 return asyncio .Lock ()
203207 return anyio .Lock ()
204-
208+
205209 # For asyncio or unknown contexts
206210 return asyncio .Lock ()
207211
@@ -256,4 +260,4 @@ def decorator(
256260 ) -> _AwaitableT :
257261 return ReAwaitable (coro (* args , ** kwargs )) # type: ignore[return-value]
258262
259- return decorator
263+ return decorator
0 commit comments