Created
February 20, 2019 03:15
-
-
Save twisteroidambassador/f35c7b17d4493d492fe36ab3e5c92202 to your computer and use it in GitHub Desktop.
Determine whether task was cancelled from inside or outside
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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