Skip to content

Commit 37643ae

Browse files
committed
Add a cancel_and_await() utility function
This is a very common pattern when cancelling a task. This also introduces a new package `util` and a module `asyncio` inside of it. Signed-off-by: Leandro Lucarella <[email protected]>
1 parent b0df5d5 commit 37643ae

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

src/frequenz/sdk/util/__init__.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
# License: MIT
2+
# Copyright © 2022 Frequenz Energy-as-a-Service GmbH
3+
4+
"""General purpose tools."""

src/frequenz/sdk/util/asyncio.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# License: MIT
2+
# Copyright © 2022 Frequenz Energy-as-a-Service GmbH
3+
4+
"""General purpose async tools."""
5+
6+
import asyncio
7+
8+
9+
async def cancel_and_await(task: asyncio.Task) -> None:
10+
"""Cancel a task and wait for it to finish.
11+
12+
The `CancelledError` is suppresed, but any other exception will be propagated.
13+
14+
Args:
15+
task: The task to be cancelled and waited for.
16+
"""
17+
task.cancel()
18+
try:
19+
await task
20+
except asyncio.CancelledError:
21+
pass

0 commit comments

Comments
 (0)