11import asyncio
2+ import sys
23import threading
34from types import TracebackType
45from typing import (
2930 anyio = None # type: ignore
3031
3132
33+ if sys .version_info >= (3 , 11 ): # pragma: nocover
34+ import asyncio as asyncio_timeout
35+
36+ anyio_shield = None
37+ else : # pragma: nocover
38+ import async_timeout as asyncio_timeout
39+
40+ if anyio is None : # pragma: nocover
41+ raise RuntimeError ("Running in Python<3.11 requires anyio" )
42+ anyio_shield = anyio .CancelScope
43+
44+
3245AsyncBackend = Literal ["asyncio" , "trio" ]
3346
3447
@@ -163,9 +176,11 @@ async def wait(self, timeout: Optional[float] = None) -> None:
163176 with trio .fail_after (timeout_or_inf ):
164177 await event .wait ()
165178 else :
166- asyncio_exc_map : ExceptionMapping = {TimeoutError : PoolTimeout }
179+ asyncio_exc_map : ExceptionMapping = {
180+ asyncio .exceptions .TimeoutError : PoolTimeout
181+ }
167182 with map_exceptions (asyncio_exc_map ):
168- async with asyncio .timeout (timeout ):
183+ async with asyncio_timeout .timeout (timeout ):
169184 await event .wait ()
170185
171186
@@ -217,8 +232,11 @@ async def shield(shielded: Callable[[], Coroutine[Any, Any, None]]) -> None:
217232 if current_async_backend () == "trio" :
218233 with trio .CancelScope (shield = True ):
219234 await shielded ()
235+ elif sys .version_info < (3 , 11 ): # pragma: nocover
236+ with anyio_shield (shield = True ):
237+ await shielded ()
220238 else :
221- await AsyncShieldCancellation ._asyncio_shield (shielded )
239+ await AsyncShieldCancellation ._asyncio_shield (shielded ) # pragma: nocover
222240
223241 @staticmethod
224242 async def _asyncio_shield (
@@ -227,7 +245,7 @@ async def _asyncio_shield(
227245 inner_task = asyncio .create_task (shielded ())
228246 try :
229247 await asyncio .shield (inner_task )
230- except asyncio .CancelledError :
248+ except ( asyncio .exceptions . CancelledError , asyncio . CancelledError ) :
231249 # Let the inner_task to complete as it was shielded from the cancellation
232250 await inner_task
233251
0 commit comments