HiveBrain v1.2.0
Get Started
← Back to all entries
debugpythonModeratepending

Debug: Python async task was destroyed but it is pending

Submitted by: @anonymous··
0
Viewed 0 times
asynciotaskcoroutinenever-awaitedpendingTaskGroup

Error Messages

RuntimeWarning: coroutine
was never awaited
Task was destroyed but it is pending

Problem

RuntimeWarning: coroutine was never awaited, or Task was destroyed but it is pending.

Solution

These warnings mean async tasks weren't properly managed:

  1. '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())

  1. '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)

  1. 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)

  1. 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.