Python:Python Async/Await and asyncio Concurrency Fundamentals
Python•Async & Concurrency

Python Async/Await and asyncio Concurrency Fundamentals

Asynchronous programming enables cooperative multitasking on a single thread. Coroutines yield control during I/O pauses using await.

Syntax

async def async_function(): await asyncio.sleep(delay) return result asyncio.run(async_function())

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
async defDeclarationDefines a coroutine function.
awaitExpressionPauses execution until the awaited awaitable completes.
asyncio.gather()UtilityRuns multiple coroutines concurrently.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Python locally:

# Python asyncio Concurrency Simulation
import asyncio

async def fetch_api_data(service_name: str, delay_sec: float):
    print(f"[{service_name}] Starting request...")
    await asyncio.sleep(delay_sec)
    print(f"[{service_name}] Received response in {delay_sec}s")
    return {"service": service_name, "status": 200}

async def main():
    print("--- Dispatching Concurrent Tasks ---")
    # Launch tasks concurrently with asyncio.gather
    results = await asyncio.gather(
        fetch_api_data("Auth-Service", 0.1),
        fetch_api_data("Payment-Gateway", 0.05),
        fetch_api_data("Analytics-Engine", 0.08)
    )
    print(f"\nAll {len(results)} services responded successfully!")

asyncio.run(main())
Expected Output:
--- Dispatching Concurrent Tasks ---
[Auth-Service] Starting request...
[Payment-Gateway] Starting request...
[Analytics-Engine] Starting request...
[Payment-Gateway] Received response in 0.05s
[Analytics-Engine] Received response in 0.08s
[Auth-Service] Received response in 0.1s

All 3 services responded successfully!

How It Works: Step-by-Step

  • Lines 4-8: Defines an async coroutine that simulates non-blocking network I/O with sleep.
  • Lines 12-17: asyncio.gather runs all three tasks in parallel instead of sequentially.
  • Line 20: asyncio.run(main()) starts the event loop and runs the entry coroutine.

Key Concepts

  • async def declares a coroutine; calling it returns a coroutine object without executing it immediately.
  • await yields control back to the event loop so other coroutines can make progress.
  • asyncio is ideal for high-concurrency network services, database calls, and web scraping.

Common Mistake: Calling an async coroutine without await or asyncio.run()

Calling async_func() without await only creates a coroutine object; the function never runs.

❌ Incorrect
async def test():
    print("hello")
test() # RuntimeWarning: coroutine was never awaited
✅ Correct
async def test():
    print("hello")
asyncio.run(test()) # Runs coroutine on event loop

Related Python Tutorials & Compiler

Run and test Python on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Python Online Compiler