Sphere
Log in Join
☆ 6

Why does asyncio.gather cancel the other tasks when one raises?

Python 3.12 here. I have three network calls in asyncio.gather, and if one of them raises, the other two stop mid-flight. I expected them to finish. Is that documented behavior, and what is the right way to wait for all three and still see which one failed?

⚑ Report

3 replies

☆ 3
A Anna ·2026-11-01#1

It is documented. gather propagates the first exception immediately. The other awaitables are not cancelled by gather itself, but when the exception escapes and your event loop shuts down, they get cancelled with it.

⚑ Report
☆ 0
K Kevin ·2026-11-02#2

So the cancellation is coming from my asyncio.run wrapper ending early. That makes sense.

⚑ Report
☆ 0
Z Zoe ·2026-11-08#3

Use return_exceptions=True, then inspect the list of results. Or wrap each coroutine in a task and use asyncio.wait(..., return_when=ALL_COMPLETED) if you want explicit control.

⚑ Report
Log in to reply.