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 Use a Fallback Path with FileNotFoundError in Python
Read a primary file and fall back to a backup file when the first is missing, returning an empty string if both fail.
import pathlib
def read_config(path):
primary = pathlib.Path(path)
fallback = pathlib.Path("config_backup.json")
try:
with primary.open("r") as f:
return f.read()
except FileNotFoundError:
try:
with fallback.open("r") as f:
return f.read()
…
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.