Python's asyncio module provides infrastructure for writing concurrent code using the async/await syntax. Asyncio allows you to execute code out of order while waiting on long-running tasks like network requests without blocking the rest of the program.
The Event Loop
At the heart of asyncio is the event loop. This keeps track of tasks, executes them when conditions are met, and puts pending tasks to sleep:
import asyncio
async def my_coro():
print('Hello world!')
loop = asyncio.get_event_loop()
loop.run_until_complete(my_coro())
loop.close()
The event loop runs the
Async Functions and Awaitables
Functions declared with
import asyncio
async def my_coro():
await some_long_running_task()
print('Done!')
loop = asyncio.get_event_loop()
loop.run_until_complete(my_coro())
While waiting on
You can
resp = await aiohttp.get('http://example.com')
print(resp)
Concurrent Execution with gather()
await asyncio.gather(
coro_1(),
coro_2(),
)
The event loop interleaves execution of
Key Takeaways
With these building blocks, you can write highly concurrent Python without threads or callbacks!