Debugging state
Inspecting objects in a debugger or interactive session.
Python · Module
__repr__ defines an object's official string representation for repr(). Make it information-rich and unambiguous, ideally resembling Python code that can recreate the value.
Define __repr__(self) to return the string produced when repr() represents an instance. Prefer a clear, information-rich result that resembles a Python expression able to recreate the value; if that is not feasible, return a useful angle-bracket description. When __str__ is absent, Python also uses this method for informal string conversion.
object.__repr__(self)| Name | Type | Description |
|---|---|---|
self | object | The instance whose official representation is being computed. |
A string object containing the object's official representation.
class User:
def __init__(self, name, role):
self.name = name
self.role = role
def __repr__(self):
return f"User(name={self.name!r}, role={self.role!r})"
user = User("Ada", "admin")
print(repr(user))The method returns a readable representation containing constructor-like field values.
Inspecting objects in a debugger or interactive session.
Logging domain objects with identifying fields.
Producing constructor-like output for value-oriented classes.
__repr__ is called by repr() to compute an object's official string representation. It should be information-rich and unambiguous, ideally resembling a valid Python expression that can recreate the value.
Follow-up: What should it return if recreation syntax is impractical? Return a string shaped like <...some useful description...>.
The method's result must be a string. A class can implement it as def __repr__(self), and the built-in repr() invokes it for instances.
Follow-up: What happens if the method returns an integer? It violates the required return type and representation fails.
If __str__ is not defined, Python uses __repr__ when an informal string representation is needed. This makes a sole __repr__ implementation affect both debugging output and informal display.
Follow-up: How does this differ from __str__? __str__ has no expectation of returning a valid Python expression and may be more convenient or concise.
repr()object.__str__()str()object