Concurrency & performance
asyncio, threading, multiprocessing, and profiling-friendly performance patterns.
How to Test HTTPX Async Client Pool Reuse with Mocks in Python
Mock an httpx.AsyncClient to verify connection pool reuse by asserting GET calls share a single client instance across concurrent async requests.
import asyncio
import httpx
from unittest.mock import AsyncMock, patch, Mock
async def fetch_with_pool(client, url, n_reuses=3):
results = []
for i in range(n_reuses):
resp = await client.get(url)
results.append(resp.status_code)
await asyncio.sleep(0) # yield to loop to mimic real us…
How to Use Array Typecodes for Compact Numeric Storage in Python
This code demonstrates how to use the `array` module with typecodes to store integers, floats, and bytes in a memory-efficient way compared to standard Python lists.
from array import array
def demonstrate_array_types():
# Compact integer arrays
small_ints = array('i', [1, 2, 3, 4, 5])
unsigned_ints = array('I', [10, 20, 30])
# Floating point arrays
floats = array('f', [1.5, 2.5, 3.5])
doubles = array('d', [1.123456789, 2.987654321])
# Charac…
Browse by section
Each section groups closely related Python snippets.
Concurrency & performance — Python code examples
What you will find here
This page collects concurrency & performance snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.