debugpythonModeratepending
Debug: Python async task was destroyed but it is pending
Viewed 0 times
asynciotaskcoroutinenever-awaitedpendingTaskGroup
Error Messages
Problem
RuntimeWarning: coroutine was never awaited, or Task was destroyed but it is pending.
Solution
These warnings mean async tasks weren't properly managed:
# BAD:
async def fetch_data(): ...
fetch_data() # Called without await!
# GOOD:
await fetch_data()
# Or if you want it running in background:
task = asyncio.create_task(fetch_data())
# BAD: Task created but never awaited/collected
asyncio.create_task(background_work())
# Task reference is lost, gets garbage collected while running
# GOOD: Keep reference and await:
task = asyncio.create_task(background_work())
# ... later:
await task
# Or collect all tasks:
tasks = []
tasks.append(asyncio.create_task(work()))
await asyncio.gather(*tasks)
async def main():
tasks = set()
task = asyncio.create_task(work())
tasks.add(task)
task.add_done_callback(tasks.discard)
try:
await asyncio.gather(*tasks)
except asyncio.CancelledError:
pass
finally:
for task in tasks:
task.cancel()
await asyncio.gather(*tasks, return_exceptions=True)
async with asyncio.TaskGroup() as tg:
tg.create_task(work1())
tg.create_task(work2())
# All tasks awaited automatically
- 'coroutine was never awaited':
# BAD:
async def fetch_data(): ...
fetch_data() # Called without await!
# GOOD:
await fetch_data()
# Or if you want it running in background:
task = asyncio.create_task(fetch_data())
- 'Task was destroyed but it is pending':
# BAD: Task created but never awaited/collected
asyncio.create_task(background_work())
# Task reference is lost, gets garbage collected while running
# GOOD: Keep reference and await:
task = asyncio.create_task(background_work())
# ... later:
await task
# Or collect all tasks:
tasks = []
tasks.append(asyncio.create_task(work()))
await asyncio.gather(*tasks)
- Proper cleanup on shutdown:
async def main():
tasks = set()
task = asyncio.create_task(work())
tasks.add(task)
task.add_done_callback(tasks.discard)
try:
await asyncio.gather(*tasks)
except asyncio.CancelledError:
pass
finally:
for task in tasks:
task.cancel()
await asyncio.gather(*tasks, return_exceptions=True)
- TaskGroup (Python 3.11+):
async with asyncio.TaskGroup() as tg:
tg.create_task(work1())
tg.create_task(work2())
# All tasks awaited automatically
Revisions (0)
No revisions yet.