Course contentsShow
← Python
Lesson 886 of 1,06014. Concurrency and PerformanceFree lesson

Defining Coroutines with Async and Await

Master the syntax for creating and calling coroutines to pause execution without blocking the main thread.

In this lesson, you will learn how to define and execute coroutines using the async and await keywords to pause execution without blocking your program.

The Coroutine Paradigm

Up until now, we have handled concurrency primarily through threading and multiprocessing, where the operating system switches between tasks. In an asynchronous model, we shift control to the application itself. A coroutine is a specialized function that can suspend its execution, yield control back to the event loop, and resume later exactly where it left off.

Defining and Awaiting

To define a coroutine, you prefix the function definition with the async keyword. Calling this function does not execute it immediately; instead, it returns a coroutine object. To actually run the code inside and handle the suspension, you use the await keyword.

Consider this example:

import asyncio

async def fetch_data():
    print("Fetching data...")
    # Simulate a non-blocking I/O operation
    await asyncio.sleep(1) 
    print("Data received!")
    return {"id": 1}

async def main():
    # Calling the coroutine and waiting for its result
    result = await fetch_data()
    print(f"Result: {result}")

# Entry point to run the top-level coroutine
asyncio.run(main())

Why This Matters

When you await a coroutine like asyncio.sleep, you are telling the Python event loop: "I am waiting for this task to complete. While I'm waiting, please go execute other tasks that are ready to run."

Unlike traditional multi-threading—where the OS preemptively switches tasks—await creates a cooperative multitasking environment. Your program explicitly identifies "yield points" where it is safe to pause. This prevents your entire application from grinding to a halt during I/O operations (like network requests or file reads) and avoids the overhead of managing OS-level threads. By using async and await, you ensure your code remains responsive, efficient, and significantly easier to reason about than complex lock-based synchronization.

Key Takeaway: Defining a function with async turns it into a coroutine, and using await allows that coroutine to pause and yield control to the event loop without blocking the main execution thread.