Reference library

Python Code Samples

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

29 matches
Automation & scripting easy

How to Deploy a Static Site Build to an Nginx Directory in Python

Copy a static site build directory into an Nginx web root using Python's shutil and pathlib modules.

automation deployment shutil
Python
import shutil
import os
from pathlib import Path

SRC_DIR = Path("build")
DEST_DIR = Path("/var/www/html")

def deploy_site(src: Path, dest: Path) -> None:
    if not src.exists():
        raise FileNotFoundError(f"Build directory not found: {src}")

    dest.mkdir(parents=True, exist_ok=True)

    for item in src.ite…
15 0 Open
Modern tooling easy

How to Mock Fabric Connections in Python for Task Testing

Create a lightweight MockConnection class to replace fabric.Connection and test task functions without SSH.

fabric mocking testing
Python
from fabric import Connection


class MockConnection:
    """Minimal mock of fabric.Connection for task testing."""

    def __init__(self):
        self.commands = []

    def run(self, command, **kwargs):
        self.commands.append(command)
        return f"OK: {command}"


def deploy(conn):
    """Deploy the app:…
13 0 Open
Observability & SRE easy

How to Create a Deployment Environment Tag in Python

Generate a standardized deployment tag string by combining service and environment names with an f-string.

deployment observability f-string
Python
def mock_env_tag(service, environment):
    return f"{service}-{environment}"

if __name__ == "__main__":
    service = "api-gateway"
    environment = "production"
    tag = mock_env_tag(service, environment)
    print(f"Deployment tag: {tag}")
13 0 Open
Observability & SRE medium

How to Implement an Error Budget Policy in Python

This code implements a mock error budget policy that decides whether to freeze deployments based on a simulated error rate and monthly freeze limits.

error-budget sre deploy-freeze
Python
from datetime import datetime, timedelta

class ErrorBudgetPolicy:
    FREEZE_WINDOW_HOURS = 24
    MAX_FREEZES_PER_MONTH = 3

    def __init__(self, budget_percentage=99.9):
        self.budget_percentage = budget_percentage
        self.freeze_count = 0
        self.last_freeze_start = None
        self.freeze_enabl…
12 0 Open
ML engineering pipelines easy

Champion Challenger Deployment Mock in Python

Simulates an A/B champion-challenger ML deployment workflow — comparing two mock model accuracies and deciding which to promote to production.

ml deployment champion-challenger
Python
import random
import time

class ModelMocker:
    def __init__(self, name="Model", accuracy=0.85):
        self.name = name
        self.accuracy = accuracy

    def predict(self, data):
        """Simulate prediction with some randomness."""
        time.sleep(0.005)  # simulate compute time
        return 1 if rando…
13 0 Open
ML engineering pipelines medium

How to Stage ML Model Workflows with Python Classes

Defines a Stage class to model ML pipeline stages with variants and mocks, printing grammar for Model, Staging, and Production stages.

ml-pipelines stages model-deployment
Python
class Stage:
    def __init__(self, name):
        self.name = name
        self.mocks = []
        self.variants = []

    def add_mock(self, mock_name):
        self.mocks.append(mock_name)

    def add_variant(self, variant_name, productions=()):
        self.variants.append((variant_name, list(productions)))

    …
11 0 Open
ML engineering pipelines easy

How to implement a canary traffic split in Python

Route incoming traffic between stable and canary model or service versions using a weight-based random split with deterministic testing.

canary traffic-split random
Python
import random


def canary_route(service_name: str, canary_weight: float = 0.2) -> str:
    """Route traffic between stable and canary versions based on weight."""
    rng = random.Random(42)  # deterministic for reproducible demo
    if rng.random() < canary_weight:
        return f"{service_name}-canary"
    return …
13 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 medium

How to Build a GitOps Argo CD Sync Mock in Python

Simulate Argo CD-style GitOps deployment sync with Python dataclasses, random success rates, and force-sync retry logic.

gitops argo-cd deployment
Python
import random
import time
from dataclasses import dataclass, field
from typing import List, Dict


@dataclass
class Application:
    name: str
    source_repo: str
    target_revision: str
    synced: bool = False
    health_status: str = "Healthy"
    history: List[Dict] = field(default_factory=list)

    def sync(se…
13 0 Open
Production deployment patterns easy

How to Deploy Staging Then Production in Python

Walk through a staged deployment mock that promotes from staging to production in sequence with Python.

deployment staging production
Python
import time

def deploy_environment(name: str) -> None:
    print(f"Deploying to {name}...")
    time.sleep(0.1)
    print(f"Deployed to {name} ✔")

def deploy_staging_then_prod() -> None:
    environments = ["staging", "production"]
    for env in environments:
        deploy_environment(env)
        if env == "stagi…
14 0 Open
Production deployment patterns easy

How to Generate a Kubernetes Deployment Manifest in Python

Generate a Kubernetes Deployment manifest as YAML from a Python dictionary using PyYAML.

kubernetes yaml deployment
Python
import yaml

deployment = {
    "apiVersion": "apps/v1",
    "kind": "Deployment",
    "metadata": {
        "name": "mock-app",
        "labels": {"app": "mock-app"}
    },
    "spec": {
        "replicas": 3,
        "selector": {
            "matchLabels": {"app": "mock-app"}
        },
        "template": {
      …
13 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 medium

How to Mock Canary Deployment Traffic Split in Python

Simulate a canary deployment's stable/canary traffic split using deterministic request hashing to mock rollout behavior with precise percentage control.

canary-deployment traffic-split simulation
Python
class CanaryDeployment:
    def __init__(self, stable_weight: float = 0.9, canary_weight: float = 0.1):
        self.stable_weight = stable_weight
        self.canary_weight = canary_weight
        self.total_weight = stable_weight + canary_weight

    def route_request(self, request_id: int) -> str:
        """Route …
14 0 Open
Production deployment patterns medium

How to Mock Image Signing Cost in Python

Create a deterministic mock signing cost calculator that predicts resource usage for image signatures before real signing infrastructure is staged.

mock signing cost-model
Python
import math
import struct


def sign_image_cost(image_signature: bytes) -> int:
    """Deterministic mock signing cost based on image signature bytes."""
    if not image_signature:
        raise ValueError("Empty image signature")
    digest = 0
    for byte in image_signature:
        digest = (digest * 31 + byte) &…
13 0 Open
Production deployment patterns easy

How to Mock Multi-Stage Docker Builds in Python

Simulate a multi-stage Docker build in pure Python using classes and temp directories to understand how build stages copy artifacts into a final image.

docker multi-stage simulation
Python
# Simulate multi-stage Docker build with pure Python
from pathlib import Path
import tempfile
import shutil

class BuildContext:
    """Mimics a Docker build context with stages."""
    
    def __init__(self, name):
        self.name = name
        self.files = {}
    
    def add_file(self, dest, content):
        s…
13 0 Open
Production deployment patterns easy

How to Mock Terraform Plan and Apply in Python

This code provides a lightweight Python mock of Terraform's plan and apply commands, helping you simulate infrastructure changes without real cloud resources.

terraform mock simulation
Python
class MockTerraform:
    def __init__(self):
        self.plans = [
            {"id": 1, "action": "create", "resource": "aws_instance.web"},
            {"id": 2, "action": "update", "resource": "aws_s3_bucket.data"},
            {"id": 3, "action": "destroy", "resource": "aws_iam_user.legacy"}
        ]
        sel…
13 0 Open
Production deployment patterns easy

How to Mock a Container Registry in Python

Build an in-memory container registry mock with push, tag listing, and manifest retrieval logic for testing deployment tooling.

containers testing mocking
Python
import json
from collections import defaultdict


class MockRegistry:
    def __init__(self):
        self.repositories = defaultdict(dict)

    def push_image(self, repo: str, tag: str, layers: list[str]) -> None:
        self.repositories[repo][tag] = {
            "layers": layers,
            "size": sum(len(layer…
13 0 Open
Production deployment patterns easy

How to Mock a GitHub Actions Workflow in Python

Build a dataclass-based model of a GitHub Actions workflow and simulate its execution to validate steps and outputs before deployment.

github-actions dataclasses mock
Python
import json
from dataclasses import dataclass, asdict
from typing import List, Dict, Any


@dataclass
class Step:
    name: str
    run: str


@dataclass
class Job:
    name: str
    steps: List[Step]
    runs_on: str = "ubuntu-latest"


@dataclass
class Workflow:
    name: str
    jobs: List[Job]

    def to_github_a…
12 0 Open
Production deployment patterns easy

How to Mock a Kubernetes Rolling Update with maxSurge in Python

Simulate a Kubernetes rolling update with maxSurge policy, tracking peak and final replica counts during roll transitions.

kubernetes rolling-update maxsurge
Python
from collections import deque

class RollingUpdateMaxSurge:
    def __init__(self, replicas, max_surge):
        self.replicas = replicas
        self.max_surge = max_surge
        self.available = replicas
        self.history = deque()

    def roll(self, desired_replicas):
        """
        Simulate a rolling upd…
11 0 Open
Production deployment patterns easy

How to Mock a SIGTERM Handler in Python

Create a graceful shutdown handler for SIGTERM and SIGINT signals, then test it by simulating a signal delivery without terminating the process.

signals graceful-shutdown sigterm
Python
import signal
import time

class Service:
    def __init__(self):
        self.running = True

    def shutdown(self, signum, frame):
        print(f"Received signal {signum}, shutting down gracefully...")
        self.running = False

    def run(self):
        signal.signal(signal.SIGTERM, self.shutdown)
        sig…
12 0 Open
Production deployment patterns easy

How to Mock an Ingress TLS Certificate Manager in Python

Build a mock TLS certificate manager for ingress that issues, checks, and renews certificates with expiry tracking — useful for testing deployment workflows before touching real infrastructure.

tls certificates ingress
Python
import ssl
import socket
from datetime import datetime, timedelta


class TLSCertManager:
    def __init__(self, hostname):
        self.hostname = hostname
        self.certificates = {}

    def request_certificate(self, domain, days_valid=90):
        """Mock a certificate issuance request that stores a cert with e…
14 0 Open
Production deployment patterns easy

How to Roll Back to a Previous Image Tag in Python

A dataclass-based mock registry that tracks image tag history and rolls back to the previous tag, useful for deployment rollback logic.

rollback deployment dataclass
Python
"""Demonstrates a rollback pattern for a Docker-style image tag registry."""

from dataclasses import dataclass, field


@dataclass
class ImageRegistry:
    """A minimal mock registry tracking current tags per image."""

    tags: dict[str, list[str]] = field(default_factory=dict)

    def push(self, image: str, tag: …
12 0 Open
Production deployment patterns medium

How to Simulate Blue-Green Deployment Switch in Python

A mock Blue-Green deployment class that deploys new versions to an inactive environment, runs a health check, switches traffic, and supports rollback in Python.

deployment blue-green mock
Python
import random
import time

class BlueGreenDeployment:
    def __init__(self, initial_env="blue"):
        self.environments = {"blue": "v1.0", "green": "v1.0"}
        self.active_env = initial_env
        self.running = True

    def deploy_new_version(self, version, target_env):
        if target_env == self.active_…
15 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.