pythonmagic-methodsrepr

What is the purpose of the __repr__ method?


For example,

def __repr__(self):
    return '<%s %s (%s:%s) %s>' % (
        self.__class__.__name__, self.urlconf_name, self.app_name,
        self.namespace, self.regex.pattern)

What is the significance/purpose of this method?


Solution

  • __repr__ should return a printable representation of the object, most likely one of the ways possible to create this object. See also documentation for repr() (which calls __repr__). __repr__ is more for developers, while __str__ is for end users.

    A simple example (interactive):

    class Point:
        def __init__(self, x, y):
            self.x = x
            self.y = y
        def __repr__(self):
            cls = self.__class__.__name__
            return f'{cls}(x={self.x!r}, y={self.y!r})'
    p = Point(1, 2)
    p
    

    Output:

    Point(x=1, y=2)