Using control flow statements like return
, break
, or continue
inside async TaskGroup or Nursery blocks leads
to counterintuitive behavior that can confuse developers and introduce bugs.
What is the potential impact?
Deferred execution in TaskGroup
In asyncio’s TaskGroup, control flow statements don’t take immediate effect. Instead, they wait for all tasks in the group to complete before
executing. This can lead to:
- Unexpected delays when tasks run longer than anticipated
- Code that appears to exit early but actually continues running
- Potential infinite loops if background tasks never complete
Lost return values in Nurseries
In Trio and AnyIO nurseries, return values can be lost if other tasks in the nursery raise exceptions:
- When a background task raises an exception, the return value from the main flow is discarded
- The nursery’s exception handling takes precedence over return values
- Silent data loss that’s difficult to debug