Writing Better Asyncio Code: Dos and Don’ts
Python’s asyncio library is powerful but comes with its own set of conventions and potential pitfalls. Let’s explore the best practices to follow and common mistakes to avoid.
Best Practices
1. Use asyncio.run()
as Your Main Entry Point
Always use asyncio.run()
to start your asyncio programs:
|
|
This function properly sets up and tears down the event loop, and handles cleanup when exceptions occur.
2. Prefer Async Context Managers
When available, use async context managers (async with
) for proper resource management:
|
|
3. Always Await Coroutines
One of the most common mistakes is forgetting to await coroutines. Always await them:
|
|
4. Handle Cancellation Gracefully
Always catch CancelledError
and clean up resources in tasks that might be cancelled:
|
|