196
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

6 Answers 6

236

__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
    Commented Dec 31, 2009 at 6:47
  • 2
    Omitted the reference: docs.python.org/reference/datamodel.html#object.__repr__
    – S.Lott
    Commented Dec 31, 2009 at 11:19
  • 1
    This should maybe use %r instead of %s: stackoverflow.com/questions/6005159/… Commented Mar 27, 2013 at 15:56
  • 55
    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). Commented Mar 27, 2013 at 18:19
  • 2
    does every class implement repr in python? Commented Oct 25, 2020 at 16:27
24

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
    Commented 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
    Commented 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
    Commented 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
    Commented Dec 31, 2009 at 7:09
21

__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

6

The __repr__ method simply tells Python how to print objects of a class

1
  • 3
    This is not true. That's what's __str__ is for.
    – nbro
    Commented Feb 8, 2021 at 15:52
3

An example to see the differences between them (I copied from this source),

>>> x=4
>>> repr(x)
'4'
>>> str(x)
'4'
>>> y='stringy'
>>> repr(y)
"'stringy'"
>>> str(y)
'stringy'

The returns of repr() and str() are identical for int x, but there's a difference between the return values for str y -- one is formal and the other is informal. One of the most important differences between the formal and informal representations is that the default implementation of __repr__ for a str value can be called as an argument to eval, and the return value would be a valid string object, like this:

>>> repr(y)
"'a string'"
>>> y2=eval(repr(y))
>>> y==y2
True

If you try to call the return value of __str__ as an argument to eval, the result won't be valid.

0

Implement repr for every class you implement. There should be no excuse. Implement str for classes which you think readability is more important of non-ambiguity.

Refer this link: https://www.pythoncentral.io/what-is-the-difference-between-str-and-repr-in-python/

1
  • Really?? Commanding others what to do? And on whose authority? Just make the case why a practice is good. People here can make up their own minds about what’s optimal for them in their particular circumstances. Commented Jul 4, 2022 at 16:05

Not the answer you're looking for? Browse other questions tagged or ask your own question.