repr And str Serve Different Readers
repr targets developers with an unambiguous form, str targets readers; containers render items with repr only, and each method falls back differently.
Code
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
# __repr__ targets developers: unambiguous, ideally re-constructible
def __repr__(self):
return f"Point({self.x}, {self.y})"
# __str__ targets end users: readable, even if it loses information
def __str__(self):
return f"({self.x}, {self.y})"
point = Point(3, 4)
print(str(point))
print(repr(point))
print(point) # print uses __str__ when available
# Containers render their items with repr only — __str__ never runs there
print([point, point])
# str() falls back to __repr__ when __str__ is missing
class OnlyRepr:
def __repr__(self):
return "repr form"
print(str(OnlyRepr()) == "repr form")
# With only __str__, repr() uses the default object repr, not your string
class OnlyStr:
def __str__(self):
return "str form"
print("repr falls back to default:", "OnlyStr object" in repr(OnlyStr()))Output
Captured from a sandboxed run of this snippet in the build pipeline.
(3, 4)
Point(3, 4)
(3, 4)
[Point(3, 4), Point(3, 4)]
True
repr falls back to default: TrueWhat the code does
repr And str Serve Different Readers comes down to the classes Point, OnlyRepr and OnlyStr and the functions __init__, __repr__ and __str__.
What to watch for
- No package manager involved — every call resolves to a built-in API.
Using it
Signature: def __init__(self, x, y)
The run emits 1 labeled section — repr falls back to default: — one per step.
Key statements
def __init__(self, x, y):
self.x, self.y = x, y
def __repr__(self):
return f"Point({self.x}, {self.y})"
def __repr__(self):
return "repr form"
Interactive Tools for This Topic
FAQ
- Are there third-party dependencies?
- No. The dependency list is empty; the code stays inside the standard library. The file defines `__init__`, `__repr__`, `__str__` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.