Coroutines and the event loop
Define coroutines with async def and run them with asyncio.run().
What Is Concurrency?
Asyncio provides cooperative concurrency: a single thread handles many tasks by switching between them whenever one is waiting for I/O.
# Traditional: blocking I/O holds the whole thread
# Asyncio: while waiting for I/O, run other coroutines
import asyncio
async def main():
print("Hello")
await asyncio.sleep(1) # yield control
print("World")
asyncio.run(main())async def — Coroutine Functions
Functions defined with async def are coroutine functions. Calling them returns a coroutine object; they only execute when awaited or scheduled.
import asyncio
async def greet(name):
return f"Hello, {name}"
result = asyncio.run(greet("Alice"))
print(result) # Hello, AliceAll lessons in this course
- Coroutines and the event loop
- await, Tasks, and Gathering
- Async Context Managers and Iterators
- Async I/O Patterns in Production