Reference library

Python Code Samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

61 matches
Microservices patterns medium

How to Mock Service Call Timeouts in Python

Simulate service calls with configurable timeouts using Mock to patch sleep and randomness, covering success and timeout cases.

microservices testing timeout
Python
import time
from unittest.mock import Mock, patch

# Simulate a service call with configurable timeout
def call_service(service_name, timeout=5):
    """Mock a service call that may time out."""
    start = time.time()
    print(f"Calling {service_name}...")
    
    # Simulate service latency (randomized for realism)…
16 0 Open
A/B testing & experimentation easy

How to Evaluate Feature Flags in Python

A Python function that evaluates boolean feature flags with user-specific overrides, returning whether a flag is enabled and the reason for the decision.

feature flags ab testing experimentation
Python
import json

def evaluate_feature_flag(feature_name, context, flag_configs):
    """
    Evaluates a boolean feature flag given a context dictionary.

    Args:
        feature_name: The name of the feature flag.
        context: A dictionary of user/request context (e.g., {"user_id": "123"}).
        flag_configs: A …
14 0 Open
A/B testing & experimentation medium

How to Mock Time for Cache TTL Testing in Python

This code demonstrates how to test a cache's TTL expiration logic by mocking time.time with unittest.mock to control the passage of time.

caching ttl unit-testing
Python
import time
from unittest.mock import patch

class ConfigCache:
    def __init__(self, ttl=60):
        self.ttl = ttl
        self._store = {}
        self._timestamps = {}

    def get(self, key):
        if key not in self._store:
            return None
        if time.time() - self._timestamps[key] > self.ttl:
  …
17 0 Open
A/B testing & experimentation easy

How to Mock a Remote Config Fetch in Python

Simulate a remote config API response with metadata, timestamps, and mock data for testing or local development.

mock config testing
Python
import json
from datetime import datetime
from typing import Any, Dict

def fetch_remote_config(mock_data: Dict[str, Any]) -> Dict[str, Any]:
    """Simulate fetching a remote config with metadata and timestamps."""
    return {
        "status": "success",
        "source": "mock",
        "fetched_at": datetime.utcn…
14 0 Open
Database scaling & optimization medium

Simulate Shard Key Cardinality in Python

Generate mock data with configurable cardinality to evaluate shard key distribution and detect hotspots in database scaling design.

sharding cardinality database
Python
import random
import string

def calculate_cardinality(values):
    """Return the number of distinct values in the given list."""
    return len(set(values))

def generate_mock_data(num_records, cardinality):
    """Generate mock records for a shard key with given cardinality."""
    possible_keys = [f"key_{i:04d}" fo…
17 0 Open
Auth & security at scale medium

How to Mock Environment Variables in Python

A context manager that injects and restores environment variables for isolated testing of config-dependent code.

env vars context manager testing
Python
import os

class EnvInjector:
    def __init__(self, mock_vars=None):
        self.mock_vars = mock_vars or {}
        self.original = {}

    def __enter__(self):
        for key, value in self.mock_vars.items():
            if key in os.environ:
                self.original[key] = os.environ[key]
            os.env…
14 0 Open
Auth & security at scale medium

How to Mock Environment Variables in Python for 12-Factor Config

Read 12-factor config from env vars and test/mock them with unittest.mock.patch.dict without touching the real environment.

environment-variables 12-factor testing
Python
import os
import json
from unittest.mock import patch

def load_config(env_prefix="APP"):
    """Read 12-factor style config from env vars"""
    required = ["DATABASE_URL", "API_KEY"]
    optional = {"PORT": "8080", "DEBUG": "false"}
    
    config = {}
    for key in required:
        full_key = f"{env_prefix}_{key…
13 0 Open
Production deployment patterns easy

Generate a docker-compose.yml with mock services in Python

Build a docker-compose.yml string from a Python dict of service names and images, then write it to a file.

docker compose yaml
Python
import yaml
from pathlib import Path

def generate_mock_compose(services: dict) -> str:
    compose = {
        "version": "3.9",
        "services": {}
    }
    
    for name, image in services.items():
        compose["services"][name] = {
            "image": image,
            "container_name": f"mock-{name}",
  …
17 0 Open
Production deployment patterns easy

How to Build a Data Helper for Production Deployment in Python

Build a reusable DataHelper class that loads configs, validates required keys, normalizes string values, and logs schema details — a production-ready data processing pattern.

json pathlib data-processing
Python
import json
from pathlib import Path
from typing import Any, Dict

class DataHelper:
    """Common data processing patterns for production deployment."""
    
    def __init__(self, config_path: str | Path):
        self.config_path = Path(config_path)
        self.config = self._load_config()
    
    def _load_confi…
14 0 Open
Production deployment patterns easy

How to Implement a Data Helper Class in Python for Production Deployments

Build an environment-aware data helper in Python that loads config, extracts, transforms, and reports on JSON data using small, testable functions.

data-helper production json
Python
"""Production-style data helper for beginners.

Demonstrates:
- environment-aware config
- central data extraction
- small, testable functions
"""

import os
import json
from pathlib import Path
from typing import List, Dict, Any


def load_config(env: str = os.getenv("APP_ENV", "development")) -> Dict[str, Any]:
    …
12 0 Open
Production deployment patterns easy

How to Merge Helm Chart Values Per Environment in Python

Merge default Helm chart values with environment-specific overrides using a recursive dictionary merge function, then write each environment's YAML file.

helm merge yaml
Python
from pathlib import Path
import json
import tempfile


DEFAULT_VALUES = {
    "image": "nginx:latest",
    "replicas": 1,
    "resources": {"cpu": "100m", "memory": "128Mi"},
}

ENV_OVERRIDES = {
    "dev": {"replicas": 1, "resources": {"cpu": "50m"}},
    "staging": {"replicas": 2, "resources": {"cpu": "250m", "memor…
11 0 Open
Production deployment patterns easy

How to Replace Fields in an Immutable Dataclass in Python

Create a new copy of a frozen dataclass with selected fields changed, leaving the original unchanged.

dataclasses immutable configuration
Python
from dataclasses import dataclass, replace


@dataclass(frozen=True)
class ServerConfig:
    name: str
    cpu: int = 2
    ram: int = 4096
    tags: tuple = ()


original = ServerConfig("web-01", cpu=4, tags=("env:prod",))
updated = replace(original, ram=8192, tags=("env:prod", "region:us-east"))

print("Original:", …
15 0 Open
Production deployment patterns medium

Mock ConfigMap Mount Environment Variables in Python

Simulate reading environment variables from a Kubernetes ConfigMap-mounted directory and test it with mocks.

kubernetes configmap mocking
Python
import os
import tempfile
from unittest.mock import patch

def load_config_from_mount(mount_path):
    """Simulate reading environment variables from a ConfigMap-mounted directory."""
    config = {}
    for filename in os.listdir(mount_path):
        file_path = os.path.join(mount_path, filename)
        if os.path.i…
14 0 Open

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

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. 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.