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
2122# Check for anyio and trio availability
@@ -42,10 +43,10 @@ def _is_in_trio_context() -> bool:
4243 """
4344 if not has_trio :
4445 return False
45-
46+
4647 # Import trio here since we already checked it's available
4748 import trio
48-
49+
4950 try :
5051 # Will raise RuntimeError if not in trio context
5152 trio .lowlevel .current_task ()
@@ -61,13 +62,13 @@ def detect_async_context() -> AsyncContext:
6162 AsyncContext: The current async context type
6263 """
6364 if not has_anyio : # pragma: no cover
64- return " asyncio"
65+ return ' asyncio'
6566
6667 if _is_in_trio_context ():
67- return " trio"
68+ return ' trio'
6869
6970 # Default to asyncio
70- return " asyncio"
71+ return ' asyncio'
7172
7273
7374_ValueType = TypeVar ('_ValueType' )
@@ -126,7 +127,9 @@ def __init__(self, coro: Awaitable[_ValueType]) -> None:
126127 """We need just an awaitable to work with."""
127128 self ._coro = coro
128129 self ._cache : _ValueType | _Sentinel = _sentinel
129- self ._lock : AsyncLock | None = None # Will be created lazily based on the backend
130+ self ._lock : AsyncLock | None = (
131+ None # Will be created lazily based on the backend
132+ )
130133
131134 def __await__ (self ) -> Generator [None , None , _ValueType ]:
132135 """
@@ -176,8 +179,9 @@ def _create_lock(self) -> AsyncLock:
176179 """Create the appropriate lock based on the current async context."""
177180 context = detect_async_context ()
178181
179- if context == " trio" and has_anyio :
182+ if context == ' trio' and has_anyio :
180183 import anyio
184+
181185 return anyio .Lock ()
182186
183187 # For asyncio or unknown contexts
@@ -228,4 +232,4 @@ def decorator(
228232 ) -> _AwaitableT :
229233 return ReAwaitable (coro (* args , ** kwargs )) # type: ignore[return-value]
230234
231- return decorator
235+ return decorator
0 commit comments