Skip to content

Commit

Permalink
Shield compatibility
Browse files Browse the repository at this point in the history
  • Loading branch information
MarkusSintonen committed Jun 10, 2024
1 parent 823c4b2 commit eb8ed67
Showing 1 changed file with 14 additions and 5 deletions.
19 changes: 14 additions & 5 deletions httpcore/_synchronization.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,16 @@
anyio = None # type: ignore


if sys.version_info >= (3, 11):
import asyncio as asyncio_timeout # pragma: nocover
else:
import async_timeout as asyncio_timeout # pragma: nocover
if sys.version_info >= (3, 11): # pragma: nocover
import asyncio as asyncio_timeout

anyio_shield = None
else: # pragma: nocover
import async_timeout as asyncio_timeout

if anyio is None: # pragma: nocover
raise RuntimeError("Running in Python<3.11 requires anyio")
anyio_shield = anyio.CancelScope


AsyncBackend = Literal["asyncio", "trio"]
Expand Down Expand Up @@ -226,6 +232,9 @@ async def shield(shielded: Callable[[], Coroutine[Any, Any, None]]) -> None:
if current_async_backend() == "trio":
with trio.CancelScope(shield=True):
await shielded()
elif sys.version_info < (3, 11):
with anyio_shield(shield=True):
await shielded()
else:
await AsyncShieldCancellation._asyncio_shield(shielded)

Expand All @@ -236,7 +245,7 @@ async def _asyncio_shield(
inner_task = asyncio.create_task(shielded())
try:
await asyncio.shield(inner_task)
except asyncio.CancelledError:
except (asyncio.exceptions.CancelledError, asyncio.CancelledError):
# Let the inner_task to complete as it was shielded from the cancellation
await inner_task

Expand Down

0 comments on commit eb8ed67

Please sign in to comment.