Reference library

Python Code Samples

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

31 matches
Errors & debugging medium

How to Add a Correlation ID to Logging Records in Python

Attach a unique correlation ID to every log record using a custom logging.Filter, making distributed request tracking traceable.

logging correlation-id filter
Python
import logging
import uuid
from dataclasses import dataclass, field


@dataclass
class CorrelationIdFilter(logging.Filter):
    correlation_id: str = field(default_factory=lambda: str(uuid.uuid4()))

    def filter(self, record: logging.LogRecord) -> bool:
        record.correlation_id = self.correlation_id
        re…
15 0 Open
Errors & debugging easy

How to Assert Preconditions with Descriptive Messages in Python

Use Python's assert statement with a custom message to validate function preconditions and fail fast with clear diagnostics.

assert debugging preconditions
Python
def divide(dividend, divisor):
    assert divisor != 0, f"Divisor must be non-zero, got {divisor!r}"
    return dividend / divisor


if __name__ == "__main__":
    print(divide(10, 2))
    try:
        divide(10, 0)
    except AssertionError as e:
        print(f"AssertionError: {e}")
16 0 Open
Errors & debugging easy

How to Assert an Invariant After a Complex Transformation in Python

Use assert to verify that a multi-step transformation preserves a mathematical invariant, catching regressions early.

assert debugging invariants
Python
def transform_value(value):
    """Apply several transformations to a value."""
    doubled = value * 2
    shifted = doubled + 10
    normalized = shifted / 2
    return int(normalized)

def assert_invariant(value):
    """Assert that the transformation preserves a key invariant."""
    original = value
    transform…
13 0 Open
Errors & debugging easy

How to Build a Simple Debug Timer in Python

Create a context manager class to time the execution of a code block with a one-line printout.

debugging context-manager performance
Python
import time


class DebugTimer:
    """Context manager that times the execution of a code block."""

    def __init__(self, label="Operation"):
        self.label = label
        self.start_time = None

    def __enter__(self):
        self.start_time = time.perf_counter()
        return self

    def __exit__(self, e…
15 0 Open
Errors & debugging easy

How to Catch ValueError in Python (try except)

Handle invalid numeric input by catching ValueError in a try/except block and returning a friendly error message.

errors exception handling valueerror
Python
def parse_number(text):
    try:
        number = int(text)
        return f"Parsed number: {number}"
    except ValueError as error:
        return f"Error: '{text}' is not a valid number ({error})"


if __name__ == "__main__":
    examples = ["42", "hello", "3.14", "100"]
    for item in examples:
        print(pars…
11 0 Open
Errors & debugging easy

How to Configure Python Logging with File Rotation

A complete demo that sets up a logger with a rotating file handler, writes several log entries, and shows the contents of the current log file.

logging file-handler rotating-file-handler
Python
import logging
from logging.handlers import RotatingFileHandler

logger = logging.getLogger("rotating_logger")
logger.setLevel(logging.DEBUG)

file_handler = RotatingFileHandler(
    "app.log",
    maxBytes=100,
    backupCount=3
)
file_handler.setFormatter(
    logging.Formatter("%(asctime)s - %(levelname)s - %(messa…
13 0 Open
Errors & debugging easy

How to Debug Print Behind a DEBUG Environment Flag in Python

Create a debug_print function that only outputs when the DEBUG environment variable is set to a truthy value like 1, true, yes, or on.

debugging environment-variables logging
Python
import os


def debug_print(*args, **kwargs):
    """Print only when DEBUG environment variable is set to a truthy value."""
    if os.environ.get("DEBUG", "").lower() in ("1", "true", "yes", "on"):
        print(*args, **kwargs)


if __name__ == "__main__":
    # Example usage: run as `DEBUG=1 python script.py` to se…
11 0 Open
Errors & debugging easy

How to Detect the Recursion Limit in Python with sys.getrecursionlimit

This Python code recursively calls itself, printing the current recursion depth and the recursion limit from sys.getrecursionlimit, and catches the RecursionError when the limit is hit.

recursion sys debugging
Python
import sys

def recurse(depth=0):
    print(f"Depth: {depth}, Recursion limit: {sys.getrecursionlimit()}")
    return recurse(depth + 1)

if __name__ == "__main__":
    try:
        recurse()
    except RecursionError:
        print("Recursion limit reached!")
        print(f"Final recursion limit: {sys.getrecursionli…
13 0 Open
Errors & debugging medium

How to Diff Two Dicts in Python for Config Drift

Recursively compare two dictionaries and report added, removed, and changed keys with their old and new values for debugging configuration drift.

dict diff config
Python
def diff_dicts(a, b, path=""):
    differences = []

    for key in a.keys() | b.keys():
        new_path = f"{path}.{key}" if path else key

        if key not in a:
            differences.append((new_path, "<missing>", b[key], "added"))
        elif key not in b:
            differences.append((new_path, a[key], "<…
12 0 Open
Errors & debugging easy

How to Dump a Debugging Repr for Unknown Types in Python

Build a fallback repr that shows dataclass fields or object attributes for any value, handy when debugging unknown types.

debugging repr dataclasses
Python
import dataclasses
from typing import Any


@dataclasses.dataclass
class Sample:
    name: str
    values: list[int]


def dump_repr(obj: Any) -> str:
    """Return a concise but complete repr for debugging unknown types."""
    if dataclasses.is_dataclass(obj):
        fields = ", ".join(
            f"{field.name}={…
12 0 Open
Errors & debugging easy

How to Emit Deprecation Warnings in Python

Use the warnings module to mark legacy classes and methods as deprecated, letting users know to switch to newer APIs.

warnings deprecation debugging
Python
import warnings


class OldAPI:
    def __init__(self):
        warnings.warn(
            "OldAPI is deprecated; use NewAPI instead.",
            DeprecationWarning,
            stacklevel=2,
        )
        self.data = []

    def add(self, item):
        warnings.warn(
            "OldAPI.add() is deprecated; us…
14 0 Open
Errors & debugging easy

How to Handle ValueError Exceptions in Python

A beginner-friendly example showing how to catch ValueError and related exceptions with try-except blocks in Python.

exceptions valueerror try-except
Python
def divide_numbers(a, b):
    try:
        result = a / b
        return f"{a} / {b} = {result}"
    except ZeroDivisionError:
        return "Error: Cannot divide by zero."
    except TypeError:
        return "Error: Please provide numbers, not strings."
    except ValueError:
        return "Error: Invalid value de…
15 0 Open
Errors & debugging easy

How to Inspect Local Variables in an except Block in Python

Capture and print local variables at the moment an exception occurs using locals() inside an except block.

debugging exception-handling locals
Python
def risky_operation(value):
    try:
        result = 10 / value
        return result
    except ZeroDivisionError as e:
        local_vars = dict(locals())
        print(f"Error: {e}")
        print("Local variables at exception:")
        for key, val in local_vars.items():
            print(f"  {key} = {val}")
   …
13 0 Open
Errors & debugging medium

How to Log Errors with Structured Fields in Python

Logs error details as structured dictionary fields using Python's logging module with extra parameters.

logging errors structured
Python
import logging
import sys

def log_structured_error(operation: str, user_id: int, status_code: int, error_msg: str):
    """Log an error with structured fields using a dictionary."""
    logger = logging.getLogger("structured_logger")
    logger.setLevel(logging.ERROR)
    
    # Create console handler if not already …
14 0 Open
Errors & debugging easy

How to Log Exceptions with traceback.format_exc in Python

Capture and log a full traceback string when an exception occurs using Python's traceback.format_exc() and logging module.

traceback logging exception
Python
import traceback
import logging

def risky_operation(value):
    return 10 / value

logging.basicConfig(level=logging.ERROR, format='%(asctime)s - %(levelname)s - %(message)s')

def main():
    try:
        result = risky_operation(0)
        print(f"Result: {result}")
    except ZeroDivisionError:
        error_msg =…
14 0 Open
Errors & debugging easy

How to Measure Python Stack Depth with inspect.stack()

Measure the current call stack depth in Python using the inspect module to understand recursion depth and debug execution context.

inspect recursion stack
Python
import inspect

def stack_depth():
    return len(inspect.stack())

def recursive_function(n):
    if n == 0:
        print(f"Base case reached. Stack depth: {stack_depth()}")
        return
    recursive_function(n - 1)

if __name__ == "__main__":
    print(f"Initial stack depth: {stack_depth()}")
    recursive_funct…
16 0 Open
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)
    …
12 0 Open
Errors & debugging easy

How to Record Last N Errors with a Ring Buffer in Python

Use collections.deque with maxlen to keep only the most recent N error messages while discarding older entries automatically.

ring-buffer deque error-handling
Python
import collections

class ErrorRecorder:
    def __init__(self, size):
        self.buffer = collections.deque(maxlen=size)

    def record_error(self, message):
        self.buffer.append(message)

    def get_errors(self):
        return list(self.buffer)

if __name__ == "__main__":
    recorder = ErrorRecorder(3)
 …
13 0 Open
Errors & debugging easy

How to Serialize an Exception to a JSON-Safe Dict in Python

Convert any Python exception into a JSON-safe dictionary with type, message, and the last few traceback lines for logging.

exceptions json logging
Python
import json
import traceback
from typing import Any


def exception_to_dict(exc: Exception) -> dict[str, Any]:
    """Convert an exception into a JSON-safe dictionary."""
    return {
        "type": type(exc).__name__,
        "message": str(exc),
        "traceback": traceback.format_exc().strip().split("\n")[-3:],
…
15 0 Open
Errors & debugging easy

How to Use pdb.post_mortem in Python

Automatically enter the Python debugger at the exact point where an uncaught exception occurred, allowing interactive inspection of the crash site.

pdb debugging exceptions
Python
import pdb
import sys

def divide(a, b):
    return a / b

def main():
    try:
        result = divide(10, 0)
        print(f"Result: {result}")
    except Exception:
        # Enter post-mortem debugging when an uncaught exception occurs
        pdb.post_mortem(sys.exc_info()[2])

if __name__ == "__main__":
    main…
13 0 Open
Errors & debugging easy

How to Use the breakpoint() Function for Interactive Debugging in Python

Insert a breakpoint() call into your code to drop into an interactive debugger session where you can inspect variables and step through execution.

debugging pdb breakpoint
Python
def calculate_total(prices, discount=0):
    """Calculates total price with optional discount."""
    subtotal = sum(prices)
    breakpoint()  # Interactive debugging session starts here
    final_total = subtotal * (1 - discount)
    return final_total


if __name__ == "__main__":
    items = [25.50, 13.25, 9.99, 5.7…
15 0 Open
Errors & debugging medium

How to parse a traceback to get the last frame in Python

Extracts the innermost frame's file, line, and function name from a Python traceback object.

traceback exceptions debugging
Python
import sys
import traceback


def parse_traceback_last_frame(exc_info):
    """Return the file, line, and function of the last (innermost) frame."""
    _, _, tb = exc_info
    last_tb = tb
    while last_tb.tb_next is not None:
        last_tb = last_tb.tb_next
    filename = last_tb.tb_frame.f_code.co_filename
    l…
13 0 Open
Errors & debugging easy

Log to stderr with Python logging basicConfig

Configure Python's logging module to send all log messages to standard error (stderr) instead of the default stderr, with a readable timestamped format.

logging stderr debugging
Python
import logging

def main():
    logging.basicConfig(
        level=logging.DEBUG,
        format="%(asctime)s — %(name)s — %(levelname)s — %(message)s",
        stream=__import__("sys").stderr,
    )
    logger = logging.getLogger("example")
    logger.debug("Debug message")
    logger.info("Info message")
    logger.…
12 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.