Readable diagnostics
Investigating values during debugging
Python · Function
repr(object) returns a printable string representation of an object. For many types it aims to produce text that can recreate an equal-valued object with eval(), while other objects use a descriptive fallback.
repr(object) produces a string intended to be a printable representation of the supplied object. For many built-in types, that string is designed so evaluating it recreates an object with the same value; other objects may use an angle-bracket description instead.
repr(object, /)| Name | Type | Description |
|---|---|---|
object | object | The object whose printable representation is requested. |
A string containing a printable representation of the object.
eval() applied to the representation string.repr().value = {"name": "Ada", "roles": ["admin", "developer"]}
text = repr(value)
print(text)
print(eval(text) == value)Creates a printable representation of a dictionary, then demonstrates that this representation can be evaluated back to an equal value for this built-in type.
Investigating values during debugging
Checking whether a built-in value has a reconstructible representation
Implementing custom object diagnostics
repr() function return?repr(object) returns a string containing a printable representation of the object. For many types, the representation is intended to produce an equal-valued object when passed to eval().
Follow-up: Can every repr() result be passed to eval()? No; the documentation explicitly describes angle-bracket fallback representations for cases where reconstruction is not available.
repr()?The function accepts one object argument and returns a string. The result is representation text, not the original object itself.
Follow-up: How can a class influence this output? It can define a method controlling what repr() returns for its instances.
repr() for its instances?A type can control the representation of its instances by defining a method. This lets custom objects provide their own printable representation.
Follow-up: What should a custom representation avoid? It should avoid implying reliable reconstruction unless the representation actually supports that use.
strasciireprlib