Errors & debugging
Handle failures gracefully, raise helpful errors, and debug with confidence.
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.
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…
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.
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…
How to Build an Error Code Enum in Python
Define an API error code enum with descriptions and build structured error payloads for HTTP responses.
from enum import Enum
class APIErrorCode(Enum):
SUCCESS = 0
BAD_REQUEST = 400
UNAUTHORIZED = 401
FORBIDDEN = 403
NOT_FOUND = 404
CONFLICT = 409
INTERNAL_ERROR = 500
def describe_error(code):
descriptions = {
APIErrorCode.SUCCESS: "Request completed successfully",
APIE…
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.
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}={…
How to Handle ValueError with try-except in Python
Build a beginner-friendly division calculator that catches ValueError and ZeroDivisionError with try-except blocks.
def get_number(prompt="Enter a number: "):
while True:
try:
value = float(input(prompt))
return value
except ValueError:
print("That's not a valid number. Please try again.")
def divide_numbers(a, b):
try:
result = a / b
return result
ex…
Implement circuit breaker open after failures demo in Python
A minimal CircuitBreaker class that calls a function and automatically 'opens' after a set number of consecutive failures, blocking further calls with a RuntimeError.
import time
from datetime import datetime
class CircuitBreaker:
def __init__(self, threshold=3):
self.threshold = threshold
self.failure_count = 0
self.is_open = False
def call(self, func, *args, **kwargs):
if self.is_open:
raise RuntimeError("Circuit is OPEN")
…
Redact secrets from log message formatter in Python
Build a custom logging.Formatter that masks passwords, API keys, and credit card numbers in log output.
import re
import logging
class RedactingFormatter(logging.Formatter):
"""Formatter that masks sensitive data in log messages."""
SENSITIVE_PATTERNS = [
(re.compile(r'password[=:]\s*\S+', re.IGNORECASE), 'password=[REDACTED]'),
(re.compile(r'api[_-]?key[=:]\s*\S+', re.IGNORECASE), 'api_key…
Browse by section
Each section groups closely related Python snippets.
Errors & debugging — Python code examples
What you will find here
This page collects errors & debugging snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
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.