Asynchronous Python
Distinguish concurrent waiting from parallel CPU execution.
On this page
The concept
An async def function produces a coroutine when called. await allows a coroutine to suspend while an awaited operation progresses, giving the event loop a chance to run other work. asyncio.gather schedules several awaitables and returns their results in input order.
This example simulates waiting with asyncio.sleep rather than making network requests. Async code does not automatically accelerate CPU-heavy calculations. Blocking operations inside a coroutine can block the event loop, so choose async-compatible I/O or an appropriate executor boundary when necessary.
Worked example
Extract the example files. From the python_from_zero directory, run the following command in a terminal. On Windows, use py in place of python3.
python3 08_professional_workflow/64_async_io/lesson.pyimport asyncio
async def fetch_label(label):
await asyncio.sleep(0.01)
return label.upper()
async def main():
results = await asyncio.gather(fetch_label("python"), fetch_label("testing"))
print(results)
if __name__ == "__main__":
asyncio.run(main())Trace the result
- fetch_label waits briefly, then returns an uppercase result.
- gather runs the two waiting operations cooperatively and preserves their result ordering.
- asyncio.run creates and manages the event loop at the synchronous entry point.
['PYTHON', 'TESTING']Line-by-line walkthrough
Line 1: import asyncio
Load asyncio (cooperative asynchronous execution). Importing makes these names available; it is not a call to every function in the module.
Lines 4–6: async def fetch_label(label):
Define the coroutine function fetch_label with input names label. Definition stores the operation rather than executing its body. An ordinary call executes a normal function; a coroutine runs when awaited/scheduled, and a generator advances when consumed. Decorators can provide a context-manager or wrapper interface. Indented statements below belong to this operation.
Line 5: await asyncio.sleep(0.01)
Await asyncio.sleep(0.01). The coroutine may suspend while the awaited operation progresses; this is not ordinary blocking sleep.
Line 6: return label.upper()
Evaluate label.upper() and return that value to the caller. This ends the current function call; subsequent statements on this execution path do not run.
Lines 9–11: async def main():
Define the coroutine function main with input names no parameters. Definition stores the operation rather than executing its body. An ordinary call executes a normal function; a coroutine runs when awaited/scheduled, and a generator advances when consumed. Decorators can provide a context-manager or wrapper interface. Indented statements below belong to this operation.
Line 10: results = await asyncio.gather(fetch_label("python"), fetch_label("testing"))
Evaluate await asyncio.gather(fetch_label('python'), fetch_label('testing')), then bind or update results with the result. Assignment itself does not imply a deep copy.
Line 11: print(results)
Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.
Lines 14–15: if __name__ == "__main__":
Enter the program entry point only during direct execution. Importing this module still creates definitions but does not run this guarded workflow.
Line 15: asyncio.run(main())
Call asyncio.run with the displayed arguments. This call may have an effect even when its return value is not assigned.
Common mistake
time.sleep blocks the event loop when called directly inside a coroutine. Also, do not call asyncio.run inside an already running event loop.