views:

806

answers:

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

+3  A: 

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.

dmazzoni
I think the reverse quotes (or 'backticks') method of getting the "representation" of an object is deprecated, and was removed for version 3.0
MatrixFrog
MatrixFrog: both true, but the current 2.x documentation still says this, which is where the quote is from.
Roger Pate
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'`.
MatrixFrog
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
Roger Pate
+5  A: 

__repr__ is used to print a human readable presentation of an object. In this case it prints the class name and some other attributes. A simple example:

>>> class Point:
...   def __init__(self, x, y):
...     self.x, self.y = x, y
...   def __repr__(self):
...     return 'Point(x=%s, y=%s)' % (self.x, self.y)
>>> p = Point(1, 2)
>>> p
Point(x=1, y=2)
lazy1
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
Omitted the reference: http://docs.python.org/reference/datamodel.html#object.__repr__
S.Lott