Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

object.__repr__

The representation method returns a string intended to identify an object unambiguously during debugging.

Version: Python 3.14; repository image, production runtime not attested

Syntax

representation = repr(obj)

The representation method returns a string intended to identify an object unambiguously during debugging.

object.__repr__

repr and !r conversion use it, and a list's representation displays its elements through repr. A reconstructible expression is desirable when possible but is not guaranteed. The result must be str.

Applying !r to the text makes its newline visible as a backslash followed by n.

class Wrong:
    def __repr__(self): return 8
try: repr(Wrong())
except TypeError: pass
else: raise AssertionError
class Fallback:
    def __repr__(self): return 'record'
assert str(Fallback())=='record'

Examples

class Token:
    def __init__(self, text): self.text=text
    def __repr__(self): return f"Token({self.text!r})"
t=Token("a\nb")
print(repr(t))
print([t])

Result

Token('a\nb')
[Token('a\nb')]

Applying !r to the text makes its newline visible as a backslash followed by n.

Sources