Categories
python

Purpose of __repr__ method?

180

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?

2

227

__repr__ should return a printable representation of the object, most likely one of the ways possible to create this object. See official documentation here. __repr__ is more for developers while __str__ is for end users.

A simple example:

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

7

  • 2

    lazy1: I primarily wanted to fix the formatting (it’s useful to have examples match up as close as possible with what they’ll see in a sample session), but I also tweaked the output format to explicitly be different from the assignment, as that greatly improves the clarity for someone confused over this, imho. (If I’ve gone to far, just re-edit, and I’ll owe you a beer.)

    – Roger Pate

    Dec 31, 2009 at 6:47

  • 2

    Omitted the reference: docs.python.org/reference/datamodel.html#object.__repr__

    – S.Lott

    Dec 31, 2009 at 11:19

  • 1

    This should maybe use %r instead of %s: stackoverflow.com/questions/6005159/…

    Mar 27, 2013 at 15:56

  • 52

    This is not really correct. __str__ is the output that is supposed to be human readable: __repr__ is supposed to be a representation readable for the Python interpreter (i.e. feeding the string to the interpreter should recreate the object). If an object does not have a __str__ method, however, __repr__ is used instead. Also as noted: this example actually prints the __str__ method of self.x and self.y: %r should be used instead of %s in the string formatting operation (since the class does not define __str__, __repr__ is actually returned anyway, but it is an anomaly).

    Mar 27, 2013 at 18:19

  • 2

    does every class implement repr in python?

    Oct 25, 2020 at 16:27

23

This is explained quite well in the Python documentation:

repr(object): Return a string containing a printable representation of an object. This is the same value yielded by conversions (reverse quotes). It is sometimes useful to be able to access this operation as an ordinary function. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a __repr__() method.

So what you’re seeing here is the default implementation of __repr__, which is useful for serialization and debugging.

4

  • 6

    I think the reverse quotes (or ‘backticks’) method of getting the “representation” of an object is deprecated, and was removed for version 3.0

    – Tyler

    Dec 31, 2009 at 7:00


  • MatrixFrog: both true, but the current 2.x documentation still says this, which is where the quote is from.

    – Roger Pate

    Dec 31, 2009 at 7:01

  • For many objects, __repr__ and __str__ are the same function. In fact, if you only define __str__, then __repr__ defaults to just calling __str__. The most obvious case where this is not true is strings themselves: str(‘stackoverflow’) returns stackoverflow but repr(‘stackoverflow’) is 'stackoverflow'.

    – Tyler

    Dec 31, 2009 at 7:05


  • 7

    You have that backwards, __repr__ never uses __str__, but the reverse might happen. See docs.python.org/reference/…

    – Roger Pate

    Dec 31, 2009 at 7:09

17

__repr__ is used by the standalone Python interpreter to display a class in printable format. Example:

~> python3.5
Python 3.5.1 (v3.5.1:37a07cee5969, Dec  5 2015, 21:12:44) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> class StackOverflowDemo:
...     def __init__(self):
...         pass
...     def __repr__(self):
...         return '<StackOverflow demo object __repr__>'
... 
>>> demo = StackOverflowDemo()
>>> demo
<StackOverflow demo object __repr__>

In cases where a __str__ method is not defined in the class, it will call the __repr__ function in an attempt to create a printable representation.

>>> str(demo)
'<StackOverflow demo object __repr__>'

Additionally, print()ing the class will call __str__ by default.


Documentation, if you please