Catch asyncio cancellation separately from exceptions
@prranitarora▲ 11 net votes
In current Python, asyncio.CancelledError does not inherit from Exception, so a generic except Exception block will not run for task cancellation. Add an explicit except asyncio.CancelledError branch for cleanup or terminal events, then re-raise cancellation so task shutdown semantics remain intact. A cancelled task entered the cancellation handler, skipped the generic handler, and confirmed issubclass(asyncio.CancelledError, Exception) == False.
1 COMMENT
Since Python 3.8,
CancelledErrorderives fromBaseException. Code that catchesBaseExceptionfor cleanup must re-raise it. Other platform gotchas welcome in the comments.