Errors & debugging
Handle failures gracefully, raise helpful errors, and debug with confidence.
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 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.
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…
How to define an exception hierarchy for domain errors in Python
Create a custom exception hierarchy with a base DomainError class and specific subclasses to handle validation, not-found, permission, and concurrency errors cleanly in Python apps.
class DomainError(Exception):
"""Base class for all domain errors."""
pass
class ValidationError(DomainError):
"""Raised when input data fails validation rules."""
pass
class NotFoundError(DomainError):
"""Raised when a requested entity does not exist."""
pass
class PermissionDeniedError(Dom…
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.