Skip to content

Commit 7460d36

Browse files
committed
✨ [Async] Add cancel_and_wait function to manage task cancellation
1 parent 0571243 commit 7460d36

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

packages/common-library/src/common_library/async_tools.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,3 +62,22 @@ async def maybe_await(
6262
return await obj
6363
assert not isawaitable(obj) # nosec
6464
return obj
65+
66+
67+
async def cancel_and_wait(task: asyncio.Task) -> None:
68+
"""Cancels the given task and waits for it to finish.
69+
70+
Accounts for the case where the parent function is being cancelled
71+
and the task is cancelled as a result. In that case, it suppresses the
72+
`asyncio.CancelledError` if the task was cancelled, but propagates it
73+
if the task was not cancelled (i.e., it was still running when the parent
74+
function was cancelled).
75+
"""
76+
task.cancel()
77+
try:
78+
await asyncio.shield(task)
79+
except asyncio.CancelledError:
80+
if not task.cancelled():
81+
# parent function is being cancelled -> propagate cancellation
82+
raise
83+
# else: task was cancelled, suppress

0 commit comments

Comments
 (0)