Reference library

Python Code Samples

Medium snippets you can copy, study, and run in the browser editor.

18 matches
Errors & debugging medium

How to Print an Exception Chain in Python for Debugging

A helper that walks an exception's __cause__ and __context__ chain, printing each level with indentation to make debugging nested errors clearer.

exception-chain debugging traceback
Python
import sys
import traceback

def pretty_exception_chain(exc):
    """Print the full exception chain with cause/context details."""
    chain = []
    current = exc
    seen = set()
    
    while current is not None and id(current) not in seen:
        seen.add(id(current))
        chain.append(current)
        curren…
11 0 Open
Errors & debugging medium

How to Re-raise Exceptions with 'raise from' in Python

Shows how to re-raise an exception with explicit context chaining using the 'raise ... from ...' syntax, so the original cause is preserved for debugging.

exceptions raise-from error-handling
Python
def divide_with_chain(a, b):
    try:
        result = a / b
        return result
    except ZeroDivisionError as original_error:
        # Re-raise with explicit chaining context
        raise ValueError("Cannot divide by zero") from original_error

def explain_chain():
    try:
        divide_with_chain(10, 0)
    …
11 0 Open
Errors & debugging medium

How to attach a request ID to exception messages in Python

This code shows how to enrich exception messages with contextual request IDs using context variables, making error logs more traceable across concurrent requests.

contextvars exception-handling logging
Python
import logging
from contextvars import ContextVar

request_id_var = ContextVar("request_id", default="unknown")

def add_request_id(exc: Exception) -> Exception:
    exc.args = (f"request_id={request_id_var.get()} | {exc.args[0]}" if exc.args else f"request_id={request_id_var.get()}",) + exc.args[1:]
    return exc

d…
12 0 Open
Comprehensions & generators medium

How to Create a Generator Context Manager in Python with contextlib

Create a custom context manager with the @contextlib.contextmanager decorator to manage resources using a generator function.

contextlib context-manager generator
Python
import contextlib

@contextlib.contextmanager
def temporary_directory():
    """Yield a string and clean up after the block exits."""
    print("Creating temp directory...")
    dir_name = "/tmp/example"
    try:
        yield dir_name
    finally:
        print(f"Removing {dir_name}...")

if __name__ == "__main__":
 …
13 0 Open
Modern tooling medium

How to Bind and Mock structlog Context in Python

Shows how to bind persistent key-value context to a structlog logger, unbind keys, and mock the logger in tests to verify context is passed correctly.

structlog logging mocking
Python
import structlog
from unittest.mock import patch

logger = structlog.get_logger()

def demo():
    logger = structlog.get_logger()
    logger = logger.bind(user_id=42, request_id="abc123")
    logger.info("user logged in", action="login")
    
    # Unbind a key
    logger = logger.unbind("user_id")
    logger.info("r…
17 0 Open
Modern tooling medium

Mocking loguru for Structured Logging in Python

Simulate loguru's structured logging with a custom mock that captures JSON-formatted log entries with bound context.

loguru logging mock
Python
import json
import sys
from io import StringIO
from unittest.mock import patch


def mock_loguru():
    # Simulate a structured logger with context binding
    class StructuredLogger:
        def __init__(self):
            self.context = {}

        def bind(self, **kwargs):
            logger = StructuredLogger()
  …
12 0 Open
Concurrency & performance medium

Graceful Shutdown Executor Context Manager in Python

A context manager that starts a background thread and ensures it stops gracefully on exit, handling timeouts and exceptions.

threading context-manager graceful-shutdown
Python
import signal
import threading
import time
from contextlib import contextmanager


@contextmanager
def graceful_shutdown_executor(timeout=5.0):
    """Context manager that runs a task and gracefully stops it on timeout or exception."""
    stop_event = threading.Event()

    def task():
        print("Task started")
 …
15 0 Open
Testing & modern typing medium

How to Mock and Stub API Calls in Playwright E2E Tests with Python

This code demonstrates how to mock and stub API responses in Playwright end-to-end tests using Python's unittest.mock patch and Playwright's APIRequestContext.

playwright e2e-testing mocking
Python
import re
from unittest.mock import patch
from playwright.sync_api import sync_playwright

def verify_api_mock(page, mock_url, mock_response):
    with patch("playwright.sync_api.APIRequestContext.get") as mock_get:
        mock_get.return_value.json.return_value = mock_response
        mock_get.return_value.status_co…
13 0 Open
System design patterns medium

Object Pool Pattern for Database Connections in Python

Implements a reusable connection pool with acquire/release and context manager support, mocking database connections with idle reuse and exhaustion handling.

object-pool connection-pool databases
Python
import time
from contextlib import contextmanager
from collections import deque


class ConnectionPool:
    def __init__(self, size=3, max_idle=5):
        self._idle = deque(maxlen=max_idle)
        self._active = set()
        self.size = size

    def _create(self):
        return {"created_at": time.time(), "queri…
12 0 Open
Reliability & rate limiting medium

How to Propagate Context Variables with asyncio in Python

Use Python's ContextVar with asyncio to carry deadline information across concurrent tasks and propagate context automatically.

contextvars asyncio concurrency
Python
import asyncio
from contextvars import ContextVar
from datetime import datetime

deadline = ContextVar("deadline", default=None)

async def worker(name):
    current = deadline.get()
    if current:
        print(f"{name} sees deadline: {current}")
    else:
        print(f"{name} sees no deadline")
    await asyncio.…
13 0 Open
Observability & SRE medium

Adding a Correlation ID to Log Context in Python

Injects a correlation ID into the logging context using a context manager and a custom log record factory so every log line includes the ID.

logging correlation-id context-manager
Python
import logging
import uuid
from contextlib import contextmanager

logging.basicConfig(level=logging.INFO, format='%(levelname)s | %(correlation_id)s | %(message)s')


@contextmanager
def correlation_id_context(correlation_id):
    """Temporarily inject a correlation_id into the logging context."""
    extra = {'correl…
15 0 Open
Microservices patterns medium

Distributed tracing with contextvars in Python

Propagate trace and span IDs across function calls using contextvars to mock distributed tracing in a single process.

tracing contextvars microservices
Python
import contextvars
import uuid
import time

_trace_context = contextvars.ContextVar("trace_context", default=None)


class TraceContext:
    def __init__(self, trace_id, parent_span_id):
        self.trace_id = trace_id
        self.parent_span_id = parent_span_id
        self.span_id = uuid.uuid4().hex[:16]
        s…
13 0 Open
Microservices patterns medium

How to Handle mTLS Certificate Rotation in Python

Detect mTLS certificate file changes by tracking modification time and hot-reload the SSL context in a running service.

mtls ssl certificate-rotation
Python
import ssl
import tempfile
import datetime
from pathlib import Path


class MTLSContext:
    def __init__(self, cert_path, key_path, ca_path):
        self.cert_path = Path(cert_path)
        self.key_path = Path(key_path)
        self.ca_path = Path(ca_path)
        self.context = None
        self.last_loaded_mtime …
13 0 Open
A/B testing & experimentation medium

How to simulate a contextual bandit in Python

Simulate a contextual multi-armed bandit with random features and epsilon-greedy action selection in Python.

bandit-algorithms simulation epsilon-greedy
Python
import random


class ContextualBandit:
    def __init__(self, n_actions=3, n_features=4):
        self.n_actions = n_actions
        self.n_features = n_features
        self.theta = [random.random() for _ in range(n_actions * n_features)]

    def mock_context(self):
        return [random.uniform(-1, 1) for _ in ra…
13 0 Open
Database scaling & optimization medium

Database Helper in Python with SQLite Scaling Optimization

Build a beginner-friendly SQLite database helper class with WAL, indexed queries, and efficient batch inserts for scaling.

sqlite database scalability
Python
import sqlite3
from contextlib import contextmanager


class DatabaseHelper:
    """Beginner-friendly helper for SQLite database operations with scaling tips."""

    def __init__(self, db_path):
        self.db_path = db_path

    @contextmanager
    def connection(self):
        """Context manager for automatic comm…
14 0 Open
Database scaling & optimization medium

How to Build a Connection Pool Reuse Mock in Python

Build a mock connection pool with context manager to track connection reuse, acquires, and releases in Python.

connection-pool context-manager database
Python
import time
from contextlib import contextmanager


class Connection:
    def __init__(self, name):
        self.name = name
        self.in_use = False
        self.busy_since = None

    def fetch(self):
        return f"data from {self.name}"


class ConnectionPool:
    def __init__(self, size=3):
        self.conn…
13 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 an mTLS Client Certificate in Python

Create a self-signed client certificate and key with OpenSSL, load them into an SSL context, and simulate an mTLS handshake in Python for testing.

mtls ssl certificates
Python
import ssl
import socket
import subprocess
import tempfile
from pathlib import Path

def create_mock_certificates():
    """Generate self-signed client certificate and key for mTLS testing."""
    with tempfile.TemporaryDirectory() as tmpdir:
        cert_path = Path(tmpdir) / "client.crt"
        key_path = Path(tmpd…
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.