187
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?

martineau
  • 119,623
  • 25
  • 170
  • 301
zjm1126
  • 63,397
  • 81
  • 173
  • 221
  • 4
    Possible duplicate of [Difference between \_\_str\_\_ and \_\_repr\_\_ in Python](http://stackoverflow.com/questions/1436703/difference-between-str-and-repr-in-python) – Vlad Bezden Feb 26 '17 at 12:00
  • 4
    For Java developers who are learning Python, the best way to look at this is as toString() in Java. – Ravi Apr 19 '18 at 23:01

6 Answers6

231

__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)
Miki Tebeka
  • 13,428
  • 4
  • 37
  • 49
  • 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.) –  Dec 31 '09 at 06:47
  • 2
    Omitted the reference: http://docs.python.org/reference/datamodel.html#object.__repr__ – S.Lott Dec 31 '09 at 11:19
  • 1
    This should maybe use %r instead of %s: http://stackoverflow.com/questions/6005159/when-to-use-r-instead-of-s-in-python – Jonathan Adelson Mar 27 '13 at 15:56
  • 54
    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). – Daniel Andersson Mar 27 '13 at 18:19
  • 2
    does every class implement repr in python? – Charlie Parker Oct 25 '20 at 16:27
  • There's a default `__repr__` for the `object` type that all types inherit from. So yes, but it's not that informative :) – Miki Tebeka Oct 26 '20 at 08:18
  • It amazes me the way some languages make things more difficult than they should be. This should be named print or printable_representation etc. I swear Swift is the better version of Python... – fontno Sep 29 '21 at 22:46
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.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
dmazzoni
  • 12,866
  • 4
  • 38
  • 34
  • 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 '09 at 07:00
  • MatrixFrog: both true, but the current 2.x documentation still says this, which is where the quote is from. –  Dec 31 '09 at 07: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 '09 at 07:05
  • 7
    You have that backwards, \_\_repr\_\_ never uses \_\_str\_\_, but the reverse might happen. See http://docs.python.org/reference/datamodel.html#object.%5F%5Frepr%5F%5F –  Dec 31 '09 at 07:09
19

__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

Jasper Kinoti
  • 501
  • 3
  • 9
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.

Anh-Thi DINH
  • 1,845
  • 1
  • 23
  • 17
-1

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/

srav
  • 7
  • 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. – Jim Ratliff Jul 04 '22 at 16:05