Skip to content

Instantly share code, notes, and snippets.

@twisteroidambassador
Created February 20, 2019 03:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save twisteroidambassador/f35c7b17d4493d492fe36ab3e5c92202 to your computer and use it in GitHub Desktop.
Save twisteroidambassador/f35c7b17d4493d492fe36ab3e5c92202 to your computer and use it in GitHub Desktop.
Determine whether task was cancelled from inside or outside
import asyncio
class CancelledFromOutside(asyncio.CancelledError):
pass
class CancelledFromInside(asyncio.CancelledError):
pass
async def distinguish_cancellation(fut):
"""Wait for a future. If cancelled, raise different exceptions depending
on who did the cancellation.
If fut was cancelled, propagate cancellation outward by raising
CancelledFromInside.
If this function was cancelled, cancel fut, and raise CancelledFromOutside.
"""
fut = asyncio.ensure_future(fut)
try:
await asyncio.wait((fut,))
except asyncio.CancelledError:
fut.cancel()
raise CancelledFromOutside
assert fut.done()
if fut.cancelled():
raise CancelledFromInside
return fut.result()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment