Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
Configure ruff linter rules in pyproject.toml with Python
Reads an existing pyproject.toml and merges common ruff linter rules into the tool.ruff section using Python's tomllib.
import tomllib
from pathlib import Path
def configure_ruff_linter_rules(project_path: str = ".") -> dict:
"""Add common ruff linter rules to pyproject.toml if missing."""
pyproject_path = Path(project_path) / "pyproject.toml"
# Default config for ruff linter with practical rules
ruff_config = {
…
How to Enforce Indentation Rules From .editorconfig in Python
A mock function that reads .editorconfig-style indentation rules (spaces or tabs, size) and fixes indentation in source code lines by tracking brace depth.
def enforce_indent(editorconfig_rules, file_content):
"""
Mock function to enforce indentation rules from .editorconfig.
Returns the content with indentation fixed (or unchanged if already compliant).
"""
indent_style = editorconfig_rules.get("indent_style", "spaces")
indent_size = int(editorco…
How to Generate a Mock devcontainer.json Config in Python
Build a reproducible devcontainer.json file with Python, composing name, image, extensions, forwarded ports, and a post-create command as a dict.
import json
from pathlib import Path
def create_devcontainer_config(
image: str = "mcr.microsoft.com/devcontainers/python:3.11",
name: str = "python-dev-container",
ports: list[int] | None = None,
post_create: str | None = None,
) -> dict:
config = {
"name": name,
"image": image,
…
How to Initialize Sentry SDK with a Mock DSN in Python
Initialize the Sentry SDK in Python with a mock DSN to test error tracking without sending real events, then verify the DSN configuration.
import sentry_sdk
# Initialize Sentry SDK with a mock DSN (no real events will be sent)
sentry_sdk.init(
dsn="https://mock-public@mock-host/mock-project",
traces_sample_rate=1.0,
environment="development",
)
# Capture a test message to confirm SDK is configured
sentry_sdk.capture_message("Test message fr…
How to List Pre-commit Hooks from YAML Config in Python
Parse a .pre-commit-config.yaml file with PyYAML and print every hook ID paired with its source repository.
import yaml
pre_commit_config = """
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- repo: https://github.com/psf/black
rev: 23.11.0
hooks:
- id: black
"""
def list_hooks(c…
How to Load envrc Files in Python
Parse and apply direnv-style envrc files to the current environment, with proper handling of variables, comments, and quotes.
import os
import tempfile
from pathlib import Path
from unittest.mock import patch
def load_envrc(envrc_path):
"""Parse an envrc-style file and apply it to the current environment."""
env_changes = {}
with open(envrc_path, "r") as f:
for line in f:
line = line.strip()
if l…
How to Read the Python Path from VS Code settings.json in Python
This code loads VS Code's settings.json file and extracts the python.defaultInterpreterPath value, with a mock demonstration for testing.
import json
from pathlib import Path
from unittest.mock import patch
def read_vscode_python_path(settings_path: Path) -> str:
"""Extract python.defaultInterpreterPath from VS Code settings.json."""
with open(settings_path, "r") as f:
settings = json.load(f)
return settings.get("python", {}).get("d…
How to build a tox multi-env matrix with mock config in Python
Simulate a tox multi-environment matrix by validating environment names and grouping extras into a readable matrix structure.
```python
import tox
def run_tox_matrix(mock_envs):
"""Simulate a tox multi-env configuration and verify mock choices."""
config = {
"tox": {
"envlist": mock_envs,
"config": {
"basepython": "python3.9",
"deps": ["pytest", "mock"],
},
…
How to configure ruff linter rules in pyproject.toml with Python
This Python script generates a pyproject.toml file with ruff linter rules, including selected and ignored rules, per-file ignores, and complexity limits.
from pathlib import Path
def configure_ruff_rules(project_dir: str = "my_project") -> None:
"""Create a pyproject.toml with ruff linter rules for mock usage."""
pyproject_path = Path(project_dir) / "pyproject.toml"
pyproject_path.parent.mkdir(parents=True, exist_ok=True)
config = """[tool.ruff]
line-…
How to set up mypy strict mode in Python
Demonstrates how to configure and run mypy in strict mode to enforce full type annotation coverage across a Python project.
from typing import Dict, Optional
def describe_user(name: str, age: int, email: Optional[str] = None) -> Dict[str, object]:
"""Build a user description dictionary with strict type annotations."""
user: Dict[str, object] = {"name": name, "age": age}
if email is not None:
user["email"] = email
…
Dependency Injection in Python for Testability
Inject a config dependency into a service so you can swap a real environment-based config for a fake one in tests.
import os
class Config:
"""Simple config loader that can be easily faked in tests."""
def get(self, key, default=None):
return os.environ.get(key, default)
class UserService:
def __init__(self, config):
self.config = config
def get_timeout(self):
return int(self.config.get(…
Create a Data Helper Class in Python
A reusable DataHelper class that saves and loads JSON and CSV files from a configurable base directory, with automatic header detection for CSV.
import json
import csv
from pathlib import Path
class DataHelper:
def __init__(self, base_path="."):
self.base_path = Path(base_path)
self.base_path.mkdir(exist_ok=True)
def save_json(self, data, filename):
path = self.base_path / filename
with open(path, "w") as f:
…
How to Build a Weighted Random Load Balancer in Python
A Python load balancer mock that distributes requests across servers based on configurable weights using a cumulative weighted random selection algorithm.
import random
from collections import Counter
SERVERS = {
"server-a": 50,
"server-b": 30,
"server-c": 20,
}
def weighted_random_server(servers: dict[str, int]) -> str:
"""Select a server based on its weight (higher weight = more likely)."""
total_weight = sum(servers.values())
rand = random.…
Singleton Config Loader in Python with Caution
Implements a singleton config loader in Python that reads JSON config files, but demonstrates the hidden gotcha of shared state across instances.
import json
from pathlib import Path
class ConfigLoader:
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
def __init__(self, config_file="config.json"):
if not hasattr(self, "loaded…
How to Mock a Slow Startup Probe in Python
Simulate slow service initialization with a configurable mock delay to test readiness probes.
import time
from dataclasses import dataclass, field
@dataclass
class StartupProbe:
name: str
min_wait_sec: float = 0.5
max_wait_sec: float = 2.0
_ready: bool = field(default=False, init=False, repr=False)
def initialize(self) -> None:
"""Simulate slow startup with a fixed mock delay."""…
How to Retry on Specific Exception Tuples in Python
A decorator-based retry pattern that retries a function only when it raises exceptions specified in a tuple, with configurable retries and delay.
import time
import random
from unittest.mock import patch
def retry_on_exceptions(retries=3, exceptions=(ValueError,), delay=0.1):
def decorator(func):
def wrapper(*args, **kwargs):
for attempt in range(retries):
try:
return func(*args, **kwargs)
…
How to implement rate limiting per API key in Python
A simple sliding-window rate limiter that tracks request timestamps per API key and rejects requests exceeding the configured limit.
import time
API_RATE_LIMITS = {"api_key_1": 5, "api_key_2": 3} # max requests per window
WINDOW_SECONDS = 10
class RateLimiter:
def __init__(self, limits, window):
self.limits = limits
self.window = window
self.requests = {key: [] for key in limits}
def allow(self, api_key):
…
How to Build a Python Latency Histogram with Mock Buckets
This code implements a mock latency histogram that records request durations into configurable buckets and outputs counts, total, and average latency.
import time
import random
from collections import Counter
class LatencyHistogram:
def __init__(self, buckets):
self.buckets = sorted(buckets)
self.counts = Counter()
self.total = 0
self.sum_latency = 0
def record(self, latency_ms):
for i, boundary in enumerate(self.bu…
How to Mock HTTP Client Latency in Python
Simulate outbound HTTP request latency with configurable ranges to test timeouts, retries, and SLO monitoring without external services.
import time
import random
def mock_latency(host: str, min_ms: int = 100, max_ms: int = 500) -> dict:
"""Simulate an outbound HTTP request with mock latency."""
latency_ms = random.randint(min_ms, max_ms)
start = time.perf_counter()
time.sleep(latency_ms / 1000)
elapsed_ms = (time.perf_counter() - …
How to Simulate Trace Sampling Head in Python
Simulate head-based probabilistic trace sampling on mock trace data with a configurable sample rate and optional seed for reproducibility.
import random
def trace_sampling_head(mock_traces, sample_rate=0.5, seed=None):
"""Simulate probabilistic trace sampling (head-based) on mock data.
Args:
mock_traces: list of trace dictionaries with a unique 'trace_id'
sample_rate: float 0.0-1.0, probability of keeping a trace
see…
How to Use Log Levels DEBUG INFO WARNING ERROR in Python
Demonstrates Python's logging levels (DEBUG, INFO, WARNING, ERROR) with basicConfig and a logger, showing how severity filtering controls output.
import logging
# Configure a mock logger to demonstrate log levels
logging.basicConfig(level=logging.DEBUG, format="%(levelname)s: %(message)s")
logger = logging.getLogger("mock_logger")
# Simulate events at each severity level
logger.debug("Detailed diagnostic info")
logger.info("General system operation")
logger.w…
How to mock Prometheus alert rule thresholds in Python
Simulate a Prometheus alert rule with a configurable threshold and duration window, firing only when the metric exceeds the threshold long enough.
import time
import random
class MetricsStore:
def __init__(self):
self.metrics = {}
def set_metric(self, name, value, labels=None):
key = (name, tuple(sorted((labels or {}).items())))
self.metrics[key] = value
def get_metric(self, name, labels=None):
key = (name, tuple(s…
Mock Health Endpoint Liveness Check in Python
Simulate a liveness endpoint that reports service health with a configurable failure rate and uptime.
import time
import random
def liveness_check(service_name: str, failure_rate: float = 0.1) -> dict:
"""Mock health check that returns liveness status with a configurable failure rate."""
healthy = random.random() > failure_rate
response = {
"service": service_name,
"status": "alive" if he…
How to Build an In-Memory Service Registry Mock in Python
A simple in-memory ServiceRegistry class to register, retrieve, list, and unregister microservice endpoints or configs using a dict, with KeyError guards.
class ServiceRegistry:
def __init__(self):
self._services = {}
def register(self, name, service):
self._services[name] = service
def unregister(self, name):
if name not in self._services:
raise KeyError(f"Service '{name}' not found")
del self._services[name]
…
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.