In Python's asyncio (3.11+), TaskGroup is used to manage multiple asynchronous tasks collectively. If you want to force stop or cancel all tasks created inside a TaskGroup, you typically do this by cancelling the TaskGroup itself, which will propagate the cancellation to all its child tasks.
Here’s how you can do it:
Example:
python
import asyncio
async def worker(name):
try:
while True:
print(f"{name} working...")
await asyncio.sleep(1)
except asyncio.CancelledError:
print(f"{name} was cancelled")
raise
async def main():
tg = asyncio.TaskGroup()
# Create some tasks
async with tg:
tg.create_task(worker("task1"))
tg.create_task(worker("task2"))
# Let them run for a bit
await asyncio.sleep(3)
# All tasks end normally when the async with block ends
async def main_with_cancellation():
tg = asyncio.TaskGroup()
try:
async with tg:
tg.create_task(worker("task1"))
tg.create_task(worker("task2"))
await asyncio.sleep(3)
print("Cancelling the task group...")
tg.cancel() # Cancel all tasks inside the group
# after cancel, the async with block will raise exception and exit
except* asyncio.CancelledError:
# Handle cancellation of child tasks
print("Tasks were cancelled")
asyncio.run(main_with_cancellation())
Key points:
tg.cancel() cancels all tasks in the group.
This causes a CancelledError in each running task.
The async with tg: exits once all tasks are done or cancelled.
If you want to cancel from outside the TaskGroup context, keep a reference to the TaskGroup or cancel the tasks individually.
Alternatively: Cancelling specific tasks inside a TaskGroup
If you keep references to the individual asyncio.Task objects returned by tg.create_task(...), you can cancel them explicitly using .cancel() on each task.
Summary
Use tg.cancel() to cancel all tasks managed by a TaskGroup.
This sends CancelledError to all child tasks.
Handle task cancellation inside the tasks by catching asyncio.CancelledError.
If you want a minimal snippet just to force stop tasks:
python
import asyncio
async def coro():
try:
while True:
print("Running...")
await asyncio.sleep(1)
except asyncio.CancelledError:
print("Cancelled!")
raise
async def main():
async with asyncio.TaskGroup() as tg:
tg.create_task(coro())
await asyncio.sleep(2)
tg.cancel()
# On exiting the with block, all tasks are cancelled and awaited
asyncio.run(main())
Let me know if you want me to elaborate on cancelling tasks in earlier Python versions or with different approaches!
Your issue involves cancellation not working as expected occasionally, and there are a couple of bugs and misunderstandings in your code snippet that cause this behavior.
Let's analyze your snippet and fix it:
Your original snippet with minimal edits for readability:
python
import asyncio
async def coro():
try:
while True:
print("Running...")
await asyncio.sleep(1)
except asyncio.CancelledError:
print("Cancelled!")
raise
async def run_coro():
async with asyncio.TaskGroup() as tg:
tg.create_task(coro())
async def main():
task = asyncio.create_task(run_coro())
asyncio.sleep(5) # <-- This is a coroutine, but not awaited
task.cancell() # <-- Typos: should be task.cancel()
asyncio.run(main())
Main problems:
asyncio.sleep(5) is never awaited — so the program immediately reaches task.cancel(), which means run_coro() is cancelled almost immediately without waiting 5 seconds.
task.cancell() is a typo — it should be task.cancel().
Even after cancel, your task run_coro() never yields control back properly because run_coro() waits for all tasks inside TaskGroup to finish on its exit from the async with block. If those tasks don't handle cancellation properly, the program may hang.
Corrected and improved version:
python
import asyncio
async def coro():
try:
while True:
print("Running...")
await asyncio.sleep(1)
except asyncio.CancelledError:
print("Cancelled!")
raise
async def run_coro():
async with asyncio.TaskGroup() as tg:
tg.create_task(coro())
async def main():
task = asyncio.create_task(run_coro())
await asyncio.sleep(5) # Await sleep so it actually waits
task.cancel() # Correct method name
try:
await task # Wait for task cancellation to finish
except asyncio.CancelledError:
print("run_coro() was cancelled")
asyncio.run(main())
Why might your coro() sometimes not finish?
If a task ignores CancelledError or swallows it without re-raising, cancellation never completes.
When you do task.cancel() on run_coro(), it cancels the TaskGroup as well. The TaskGroup tries to wait for all children to finish. If a child coro() hangs or ignores cancellation, the group never finishes.
Also, if the TaskGroup is created inside an async context manager (async with), the context manager waits for all tasks to complete or error. If a task is stuck or misbehaving on cancellation, the whole group hangs.
Best practices to ensure cancellation works reliably:
Always re-raise asyncio.CancelledError in tasks — you are already doing this correctly.
Avoid swallowing the exception or catching generic exceptions without re-raise.
Use await when you sleep, otherwise delay is not honored.
When cancelling a task, always await it afterward to ensure it is fully cleaned up.
If you want to cancel tasks inside TaskGroup individually, you'd need to keep references to those tasks, but usually cancelling the parent task that runs the group is enough.
If coro() still doesn't cancel:
Ensure you're using Python 3.11+, since asyncio.TaskGroup is new in 3.11.
Make sure you always re-raise CancelledError in every function involved.
For long-running blocking calls inside your coroutines, cancellation might be delayed until the code reaches an await point.
Feel free to ask if you want help on debugging a specific hang or a different pattern for cancellation!
Thanks for clarifying that await task never finishes — that typically means the run_coro() task is stuck waiting for something that never completes, preventing the cancellation from fully propagating.
Why does it hang?
Your run_coro() uses an async with asyncio.TaskGroup() as tg: block.
When run_coro() is cancelled (via task.cancel()), the coroutine is interrupted.
But when the context manager of TaskGroup exits (exiting the async with block), it implicitly waits for all child tasks to finish.
If child task(s) (coro() in your case) don't get cancelled correctly or take too long to cancel, the context manager waits indefinitely.
Since the TaskGroup must wait for every child task to finish, and cancellation is not propagated properly or fully handled, await task blocks.
The root cause:
The TaskGroup context manager only returns after all children complete or error out.
Cancelling the outer task cancels the TaskGroup, which propogates CancelledError to children.
Children should properly handle CancelledError and exit swiftly.
But if for some reason a child somehow ignores or delays cancellation, or blocks on something non-cancellable, the context manager hangs.
How to fix?
Make sure coro() responds promptly to cancellation.
Your coro() should be:
python
async def coro():
try:
while True:
print("Running...")
await asyncio.sleep(1) # await is cancellable
except asyncio.CancelledError:
print("Cancelled!")
raise
You already have this. So theoretically it should cancel correctly.
Double-check that run_coro() doesn't swallow CancelledError
As run_coro() is only the context manager for the group, no extra try/except needed.
When cancelling outer task (run_coro()), TaskGroup cancels child tasks.
Therefore, task cancellation propagates.
Minimal fix: Add a cancellation handler in run_coro() — the key is explicitly cancelling the TaskGroup
Unfortunately, asyncio.TaskGroup does not have a .cancel() method. Instead, cancel the task that runs the group:
Your outer task.cancel() is correct, but sometimes outer task cancellation may be delayed due to the context manager awaiting tasks.
Alternative approach: manage cancellation manually
If the problem persists, try explicitly cancelling tasks inside the group right after creation.
Example:
python
import asyncio
async def coro():
try:
while True:
print("Running...")
await asyncio.sleep(1)
except asyncio.CancelledError:
print("Cancelled!")
raise
async def run_coro():
async with asyncio.TaskGroup() as tg:
task = tg.create_task(coro())
# Run for some time, then cancel child task manually:
await asyncio.sleep(10)
print("Cancelling child task inside TaskGroup")
task.cancel()
async def main():
# This will wait until run_coro() finishes, including cancellation/finalization
await run_coro()
asyncio.run(main())
But I guess your question is about cancelling from outside.
To cancel the run_coro() task and force termination:
When cancelling a task that runs a TaskGroup via async with, TaskGroup waits for all children to finish.
If any child (or the parent) ignores cancellation or is stuck, await task never returns.
Your child tasks (coro()) must respond quickly to cancellation by using cancellable awaits and re-raising CancelledError.
For external cancellation to succeed:
await asyncio.sleep() (or other cancellable suspensions) in your task,
propagate cancellation exceptions properly.
Consider adding a timeout/fallback using asyncio.wait_for() to avoid indefinite hangs.
If TaskGroup proves problematic, manage cancellation manually per-task.
Let me know if you want me to help investigate your exact environment or provide a minimal reproducible example!
Great question! The reason you need to re-raiseasyncio.CancelledError is to properly propagate the cancellation signal through the task hierarchy and ensure that the asyncio event loop can correctly manage task shutdown.
Why re-raise asyncio.CancelledError?
When asyncio cancels a task (via .cancel()), it injects a CancelledError into the running coroutine. This exception signals "please stop what you're doing and exit now."
If you catchCancelledError but don't re-raise it, you effectively swallow the cancellation signal.
The task believes it was asked to cancel but then "forgets" about it and continues running as if nothing happened.
This breaks the cancellation mechanism — the task keeps running when the caller expects it to stop.
The event loop and any awaiting code waiting on that task never get notified that the task ended early due to cancellation.
This can cause your program to hang or leak resources.
How asyncio uses CancelledError
You call task.cancel().
asyncio raises CancelledError inside the coroutine on next suspension point (i.e. at await or yield).
Your coroutine’s except asyncio.CancelledError: block catches it.
If you want to clean up resources (close files, release locks, etc.), you can run cleanup code here.
But after cleanup you should re-raise the CancelledError to let asyncio know cancellation continued and the task ended.
If you don't re-raise, asyncio assumes your coroutine handled cancellation and will consider the task completed normally.
Example:
python
import asyncio
async def task():
try:
while True:
print("Running...")
await asyncio.sleep(1)
except asyncio.CancelledError:
print("Cancelled! Cleaning up...")
# do cleanup here
raise # important to re-raise!
async def main():
t = asyncio.create_task(task())
await asyncio.sleep(3)
t.cancel()
try:
await t
except asyncio.CancelledError:
print("Task is cancelled from main")
asyncio.run(main())
Output:
code
Running...
Running...
Running...
Cancelled! Cleaning up...
Task is cancelled from main
What if you don't re-raise?
python
async def task():
try:
while True:
print("Running...")
await asyncio.sleep(1)
except asyncio.CancelledError:
print("Cancelled but not re-raising!")
# forgot to re-raise!
async def main():
t = asyncio.create_task(task())
await asyncio.sleep(3)
t.cancel()
await t
print("main finished waiting for task")
asyncio.run(main())
Output:
code
Running...
Running...
Running...
Cancelled but not re-raising!
main finished waiting for task
Notice that main never sees an exception.
task() thinks it handled cancellation and ended normally.
But the task never truly stopped if there were more code after the except or if it continued looping.
It allows the event loop and code awaiting the task to know the task was cancelled.
It prevents tasks from ignoring cancellations silently, avoiding hangs or resource leaks.
Recommended practice is catch the exception only to clean up, then always raise it again.
Let me know if you want examples on how to handle cleanup properly or best cancellation practices!
Good question! The except* syntax was introduced in Python 3.11 for exception groups to handle multiple exceptions simultaneously, which can arise especially with concurrency primitives like asyncio.TaskGroup.
When should you use except* versus except?
Use except asyncio.CancelledError: when you want to catch a single CancelledError from a single coroutine or task.
Use except* asyncio.CancelledError: when you are working with concurrency features (like asyncio.TaskGroup) that may raise an exception group (BaseExceptionGroup), which contains multiple exceptions raised by multiple concurrent tasks.
What is an Exception Group?
In Python 3.11+, when multiple tasks fail concurrently (e.g. multiple tasks inside a TaskGroup), Python aggregates their exceptions into an exception group (ExceptionGroup or BaseExceptionGroup). This allows raising multiple exceptions together, rather than just one.
Example with asyncio.TaskGroup raising exceptions:
python
import asyncio
async def fail(i):
await asyncio.sleep(i)
raise asyncio.CancelledError(f"Task {i} cancelled")
async def main():
tg = asyncio.TaskGroup()
try:
async with tg:
tg.create_task(fail(0.1))
tg.create_task(fail(0.2))
except* asyncio.CancelledError as e:
print(f"Caught exception group with {len(e.exceptions)} cancelled tasks!")
for exc in e.exceptions:
print(f" - {exc}")
asyncio.run(main())
Output:
code
Caught exception group with 2 cancelled tasks!
- Task 0.1 cancelled
- Task 0.2 cancelled
So: When to use except* with asyncio.CancelledError?
If you expect multiple concurrent cancellations potentially combined as an exception group, e.g., when awaiting a TaskGroup or gathering multiple tasks.
If you just have a single task/coroutine and expect one cancellation, use normal except asyncio.CancelledError.
Key points:
Use case
Use except or except*?
Catch single cancellation in one task
except asyncio.CancelledError:
Catch multiple cancellations from many tasks (TaskGroup) in one block
except* asyncio.CancelledError:
Generic error handling of multiple errors in groups
except* Exception:
Important
except* catches exception groups and filters exceptions of given type.
The caught e in except* is an instance of ExceptionGroup with attribute .exceptions — a list of all caught exceptions.
Summary
For normal cancellation handling in one coroutine, stick to normal: