repr() is Python’s built-in function (and special method __repr__) that returns an official, unambiguous string representation of an object — one that ideally allows reconstruction of the object via eval() (for simple types) or at least provides clear debugging information. In 2026, repr() remains essential in data science (pandas/Polars/Dask object inspection, logging complex structures), software engineering (debugging, custom class display, REPL output), and metaprogramming (safe serialization, AST generation) — powering print(repr(obj)), !r in f-strings, and automatic display in Jupyter/IPython notebooks.
Here’s a complete, practical guide to using repr() in Python: basic usage, custom __repr__, real-world patterns (earthquake event display, debugging pipelines, safe logging), and modern best practices with type hints, performance, safety, and integration with pandas/Polars/Dask/dataclasses/pprint/rich.
Basic repr() — official string representation of objects.
print(repr(42)) # '42' (eval-safe)
print(repr("hello\nworld")) # "'hello\\nworld'" (escapes quotes & newlines)
print(repr([1, 2, 3])) # '[1, 2, 3]'
print(repr({'a': 1, 'b': 2})) # "{'a': 1, 'b': 2}"
print(repr(None)) # 'None'
print(repr(float('nan'))) # 'nan'
Custom __repr__ — control how your classes display in print/repl/debug.
class Earthquake:
def __init__(self, mag, place, time):
self.mag = mag
self.place = place
self.time = time
def __repr__(self):
return f"Earthquake(mag={self.mag:.1f}, place={self.place!r}, time={self.time!r})"
eq = Earthquake(7.2, "Japan", "2025-03-01")
print(eq) # Earthquake(mag=7.2, place='Japan', time='2025-03-01')
print(repr(eq)) # same as above
print(f"Event: {eq!r}") # Event: Earthquake(mag=7.2, place='Japan', time='2025-03-01')
Real-world pattern: earthquake data inspection & debugging — clean repr for complex objects.
import pandas as pd
from dataclasses import dataclass
@dataclass
class Quake:
mag: float
place: str
time: str
def __repr__(self):
return f"Quake({self.mag:.1f} in {self.place!r} at {self.time})"
# From DataFrame
df = pd.DataFrame({
'mag': [7.2, 6.8, 5.9],
'place': ['Japan', 'Chile', 'Alaska'],
'time': ['2025-03-01', '2025-03-02', '2025-03-03']
})
quakes = [Quake(row.mag, row.place, row.time) for _, row in df.iterrows()]
# Clean display
for q in quakes:
print(repr(q))
# Quake(7.2 in 'Japan' at '2025-03-01')
# ...
# Debugging: repr of DataFrame subset
print(repr(df.head(2))) # shows full repr with quotes & escapes
Best practices for repr() in Python & data workflows. Prefer __repr__ over __str__ — for unambiguous, eval-safe output; __str__ for user-friendly display. Modern tip: use Polars/Dask — override __repr__ in custom classes for clean display. Use !r in f-strings — f"{obj!r}" for repr. Use pprint.pprint(obj) — pretty-print complex structures. Use reprlib.repr(obj) — truncated repr for large objects. Add type hints — def __repr__(self) -> str: .... Use repr() in logging — logger.debug(f"Event: {event!r}"). Use repr() in tests — assert repr(obj) == "Expected(...)". Use eval(repr(obj)) == obj — round-trip test for simple objects. Use __repr__ in dataclasses — auto-generated is good; override for custom format. Use __repr__ in Pydantic — model.model_dump() or custom repr. Use rich — console.print(obj) for styled repr. Use repr() with ast.literal_eval — safe reconstruction of simple literals. Use repr() in error messages — raise ValueError(f"Invalid: {value!r}"). Use repr() in Jupyter — automatic display uses __repr__. Use repr() with pprint — pprint.pformat(obj) for pretty strings. Use repr() for serialization — safe alternative to pickle for simple objects. Use repr() in debuggers — inspect object state. Use repr() with copy.deepcopy — test reconstruction.
repr(obj) returns the official string representation of an object — unambiguous, often eval-safe, and customizable via __repr__. In 2026, use for debugging, logging, safe serialization, and clean display in pandas/Polars/Dask objects. Master repr(), and you’ll make your classes self-documenting, debuggable, and easy to inspect in any Python project.
Next time you need to see what an object really is — use repr(). It’s Python’s cleanest way to say: “Show me this object exactly — with enough detail to understand or recreate it.”