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.
Python code
29 linesimport 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}={getattr(obj, field.name)!r}"
for field in dataclasses.fields(obj)
)
return f"{type(obj).__name__}({fields})"
if hasattr(obj, "__dict__"):
attrs = ", ".join(f"{k}={v!r}" for k, v in vars(obj).items())
return f"{type(obj).__name__}({attrs})"
return repr(obj)
if __name__ == "__main__":
sample = Sample(name="demo", values=[1, 2, 3])
print(dump_repr(sample))
print(dump_repr(42))
print(dump_repr([10, 20]))
Output
Sample(name='demo', values=[1, 2, 3])
42
[10, 20]
How it works
The dump_repr function first checks whether the object is a dataclass using dataclasses.is_dataclass, then reproduces a readable field list via dataclasses.fields. If the object has a __dict__ (like most classes), it iterates vars(obj) to include instance attributes. Otherwise it falls back to the built-in repr. Using !r inside f-strings ensures each value is displayed with its own repr, preserving quoting for strings.
Common mistakes
- Forgetting to handle dataclasses before generic `__dict__` objects, which would miss default field values.
- Assuming every object has `__dict__`, but some use `__slots__` — consider adding a `__slots__` branch.
- Calling `repr` without considering recursion or circular references in nested objects.
Variations
- Use `pprint.pformat` to pretty-print the dict of an object for more readable output.
- Add a `__slots__` handler that iterates `obj.__slots__` for classes that define them.
Real-world use cases
- Logging unexpected exceptions with a readable snapshot of the offending object in a web framework.
- Inspecting third-party API response objects that lack a custom `__repr__` for debugging sessions.
- Writing a custom debugger or test harness that prints state summaries for arbitrary mock objects.
Sponsored
More from Errors & debugging
- Catch RecursionError and Fail Gracefully in Python easy
- Catch ValueError and print friendly message in Python easy
- Collect Multiple Validation Errors in Python Before Raising medium
- Handle ValueError and ZeroDivisionError in Python with try except easy
- How to Add a Correlation ID to Logging Records in Python medium
- How to Assert Preconditions with Descriptive Messages in Python easy
Keep learning
Related tutorials and quizzes for this topic.