Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
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.
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…
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.
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:…
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.
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}")
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.
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…
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.
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 …
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.
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…
How to Deploy Staging Then Production in Python
Walk through a staged deployment mock that promotes from staging to production in sequence with 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…
How to Generate a Kubernetes Deployment Manifest in Python
Generate a Kubernetes Deployment manifest as YAML from a Python dictionary using PyYAML.
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": {
…
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.
"""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]:
…
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.
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…
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.
# 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…
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.
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…
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.
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…
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.
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…
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.
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…
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.
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…
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.
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…
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.
"""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: …
How to build a maintenance mode page in Python
Mock a service maintenance status page that computes remaining downtime and lists affected features from a simple class.
from datetime import datetime
class MaintenanceMode:
"""Mock a maintenance mode status page for a service."""
def __init__(self, service_name: str, scheduled_end: str):
self.service_name = service_name
self.scheduled_end = datetime.fromisoformat(scheduled_end)
self.affected_featur…
How to hide incomplete mock features with a Python feature toggle
A simple decorator-based feature toggle that returns a placeholder when a mock feature is disabled, so incomplete code can ship safely.
import functools
class FeatureToggle:
def __init__(self, enabled=False):
self.enabled = enabled
def feature(self, func=None):
"""Decorator to conditionally enable a feature."""
if func is None:
return self.feature
@functools.wraps(func)
def wrapper(*args,…
How to simulate a database migration init container mock in Python
A mock init container that runs environment checks and a staged database migration job before the main application starts, printing progress to stdout.
```python
class MigrationJob:
def __init__(self, name, steps):
self.name = name
self.steps = steps
self.current_step = 0
self.status = "pending"
def run(self):
print(f"Initializing migration job: {self.name}")
for step in self.steps:
self.current_ste…
PodDisruptionBudget minAvailable in Python
Simulate a Kubernetes PodDisruptionBudget check for minAvailable and maxUnavailable constraints with a Python class.
class PodDisruptionBudget:
def __init__(self, name, min_available=None, max_unavailable=None):
self.name = name
self.min_available = min_available
self.max_unavailable = max_unavailable
def check_availability(self, ready_pods):
if self.min_available is not None:
ret…
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.