Use __repr__ to show the programmer's representation (was: Need help understanding list structure)

Ben Finney ben+python at benfinney.id.au
Tue May 3 14:14:39 EDT 2016


Dan Strohl via Python-list <python-list at python.org> writes:

> One other point for you, if your "__repr__(self)" code is the same as
> the "__str__(self)" code (which it looks like it is, at a glance at
> least), you can instead reference the __str__ method and save having a
> duplicate code block...

Alternatively, consider: the ‘__repr__’ method is intended to return a
*programmer's* representation of the object. Commonly, this is text
which looks like the Python expression which would create an equal
instance::

    >>> foo = datetime.date.fromtimestamp(13012345678)
    >>> print(repr(foo))
    datetime.date(2382, 5, 7)

So if there is a sensible “here is the expression that could have been
used to create this instance” text, have the ‘__repr__’ method return
that text::

    >>> foo = LoremIpsum(bingle, bongle, bungle)
    >>> print(repr(foo))
    packagename.LoremIpsum("spam", 753, frob=True)

That text is very useful because it can be fed back into the interactive
interpreter to make an equal-valued instance and experiment further.

For some types, there isn't such an expression that would evaluate to an
equal-valued instance of the type. So the conventional non-evaluating
representation is used::

    >>> foo = frobnicate_the_widget(widget)
    >>> print(repr(foo))
    <LoremIpsum instance, foo: "spam" bar: 753>

This gives the crucial information of what the type is, and also gives
other interesting (to the programmer) attributes that characterise the
specific instance.

The fallback “<LoremIpsum instance at 0xDEADBEEF>” is the least helpful;
it gives the type and identity of the instance, but only because that's
the lowest common information ‘object’ can guarantee. Always implement a
more informative representation for your custom type, if you can.

-- 
 \        “Intellectual property is to the 21st century what the slave |
  `\                              trade was to the 16th.” —David Mertz |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list