Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
How to Calculate Cloud Cost Estimates with a Python Dictionary
Mocks a cloud pricing calculator using a dictionary of service rates and computes total estimated cost for given service hours.
def estimate_cost(service, hours, rate_table=None):
if rate_table is None:
rate_table = {
"basic": 50,
"standard": 75,
"premium": 100
}
if service not in rate_table:
raise ValueError(f"Unknown service: {service}")
return rate_table[service] * hour…
Build a Recipe Runner Mock in Python
A Python script that mocks a command runner recipe system: maps recipe names to shell commands, executes them with subprocess, and prints the output and exit code.
import subprocess
import sys
def run_recipe(recipe: str) -> None:
"""Simulate a command runner recipe by printing the command and exit code."""
print(f"Running recipe: {recipe}")
result = subprocess.run(recipe, shell=True, capture_output=True, text=True)
print(f"Exit code: {result.returncode}")
i…
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 Serialize a Dataclass to JSON in Python
Serialize a Python dataclass instance to JSON using asdict and json.dumps for API responses or mocks.
from dataclasses import dataclass, asdict
import json
@dataclass
class UserResponse:
id: int
name: str
email: str
active: bool = True
if __name__ == "__main__":
response = UserResponse(id=42, name="Ada Lovelace", email="ada@example.com")
print(json.dumps(asdict(response), indent=2))
How to Mock Kafka Topic Partitions with a Python dict of lists
Mocks a Kafka topic and its partitions using a defaultdict of lists to simulate message production, consumption, and per-partition counts.
from collections import defaultdict
class KafkaTopicPartitionMock:
"""A simple mock for Kafka topic-partition assignment using dict of lists."""
def __init__(self, topic):
self.topic = topic
self.partitions = defaultdict(list) # partition_id -> list of messages
def produce(self, message…
How to Implement Namespaced Cache Keys for Tenant Isolation in Python
Build a tenant-aware cache wrapper that prefixes keys with tenant and namespace, and test it with mocks.
from keyvaluestore import SimpleCache
from unittest.mock import patch
class TenantCache(SimpleCache):
def __init__(self, tenant_id, namespace="default"):
super().__init__()
self.tenant_id = tenant_id
self.namespace = namespace
def _key(self, key):
return f"tenant:{self.tenant_…
How to create a stable cache key from function arguments in Python
Generate a stable SHA-256 cache key from normalized function arguments, with keyword order normalized and tests using mocks.
import hashlib
import json
from unittest.mock import Mock
def make_cache_key(*args, **kwargs):
"""Normalize args/kwargs into a stable hash key for caching."""
normalized = {
"args": [repr(arg) for arg in args],
"kwargs": {key: repr(value) for key, value in sorted(kwargs.items())}
}
pa…
How to Mock a Schema Registry Avro Record in Python
Encode a Python dict into Avro binary using an inline schema, mimicking a schema registry record for tests or mocks.
import io
from avro.schema import parse
from avro.io import DatumWriter, BinaryEncoder
schema_json = """
{
"type": "record",
"name": "User",
"fields": [
{"name": "name", "type": "string"},
{"name": "age", "type": "int"},
{"name": "email", "type": ["null", "string"], "default": null}
]
}
"""
schem…
How to mock an external service in Python with an anti-corruption facade
This code implements an anti-corruption facade that mocks an external API, allowing client code to interact with a simulated service while keeping the same interface.
class AntiCorruptionFacade:
"""Mocks a real API while keeping the same interface."""
def __init__(self, data_store):
self._data_store = data_store
self._calls = []
def get_user(self, user_id):
self._calls.append(f"get_user({user_id})")
return self._data_store.get(u…
How to Do Random Assignment in Python for A/B Tests
Assign each item to a binary group (0 or 1) with uniform probability using a small reusable function, optionally weighted, for A/B testing mocks.
import random
def random_assignment_uniform_mock(items, weights=None):
"""Assign each item to a group (0 or 1) with uniform probability."""
if weights is None:
# Default: each item independently gets 0 or 1 with 50% probability
return [random.randint(0, 1) for _ in items]
# Optional weight…
How to Replicate Data Across All Shards in Python
Mocks a global table that replicates a key-value pair to every shard, ensuring reads return the same value from any shard.
from dataclasses import dataclass
from typing import Dict, List
@dataclass
class Shard:
id: str
data: Dict[str, int]
class GlobalTable:
def __init__(self, shards: List[Shard]):
self._shards = {s.id: s for s in shards}
def set_value(self, key: str, value: int) -> None:
"""Replicate …
How to Mock time.sleep in a Python PreStop Hook
This code simulates a Kubernetes PreStop hook that delays shutdown, then mocks time.sleep to verify the hook logic without real delay.
import subprocess
import sys
import time
from unittest.mock import patch
def pre_stop_hook():
"""Simulate a Kubernetes PreStop hook that sleeps before shutdown."""
print("PreStop hook started: delaying shutdown")
time.sleep(3)
print("PreStop hook completed: ready to shutdown")
if __name__ == "__main_…
Browse by section
Each section groups closely related Python snippets.
Guide: free Python code samples library
Copy-ready Python snippets for learners and developers
PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.
How to use this library
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- Run it in the IDE, tweak values, then take a related quiz or tutorial lesson
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.