How to Fix RuntimeWarning: coroutine was never awaited in Python
In this tutorial, you'll learn about How to Fix RuntimeWarning: Coroutine was never awaited in Python. We cover key concepts, practical examples, and best practices.
Python raises RuntimeWarning: coroutine 'X' was never awaited when an async function (coroutine) is called but the returned coroutine object is never scheduled for execution.
The Wrong Way
import asyncio
async def fetch_user(user_id):
await asyncio.sleep(1)
return {"id": user_id, "name": "Alice"}
result = fetch_user(1) # forgot await
print(result)
This produces:
<stdin>:1: RuntimeWarning: coroutine 'fetch_user' was never awaited
<coroutine object fetch_user at 0x7f8abc123>
The Right Way
Await the coroutine inside an async context:
import asyncio
async def fetch_user(user_id):
await asyncio.sleep(1)
return {"id": user_id, "name": "Alice"}
async def main():
result = await fetch_user(1)
print(result)
asyncio.run(main())
Output:
{'id': 1, 'name': 'Alice'}
Step-by-Step Fix
1. Check all await keywords are present
async def get_data():
return [1, 2, 3]
async def main():
data = get_data() # missing await
data = await get_data() # correct
2. Use asyncio.run() properly
import asyncio
async def main():
await asyncio.sleep(1)
print("Done")
# Correct
asyncio.run(main())
# Wrong -- main() is a coroutine object, not executed
main()
3. Use create_task for concurrent execution
async def background_task():
await asyncio.sleep(5)
print("Background done")
async def main():
task = asyncio.create_task(background_task())
print("Main continues...")
await task # need to await the task
asyncio.run(main())
4. Handle warnings as errors in CI
python3 -W error::RuntimeWarning script.py
This turns the warning into an exception for enforcement.
Prevention Tips
- Always add
awaitbefore calling async functions. - Use linters like
flake8-asyncto catch missing awaits. - Run with
-W error::RuntimeWarningin CI to catch these warnings. - Use
asyncio.run()as the main entry point. - Never discard coroutine objects -- always await or schedule them.
Common Mistakes with coroutine never awaited
- Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro