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:
| Parameter | Type | Description |
|---|---|---|
| async def | Declaration | Defines a coroutine function. |
| await | Expression | Pauses execution until the awaited awaitable completes. |
| asyncio.gather() | Utility | Runs multiple coroutines concurrently. |
Ready-to-Run Code Example
Executable in CompilraRun 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 loopRelated Python Tutorials & Compiler
Python Functions (def): Arguments, *args, **kwargs & Return
Functions are organized, reusable blocks of code defined using the def keyword to perform a specific action.
Python File Handling: Reading, Writing, and with open()
Learn how to read and write files safely in Python using context managers with the open() function.
Python Exception Handling: try, except, else, and finally
Exceptions in Python are handled gracefully using try...except blocks to catch runtime errors without crashing.
Python Online Compiler
Open in Compilra IDE
Run and test Python on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.