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.

Easy Python 3.9+ Aug 9, 2026 Errors & debugging 13 views 0 copies

Python code

29 lines
Python 3.9+
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}={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

stdout
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

  1. Use `pprint.pformat` to pretty-print the dict of an object for more readable output.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Errors & debugging

Related tutorials and quizzes for this topic.