Rich __repr__

Ben Finney bignose+hates-spam at benfinney.id.au
Tue Nov 1 18:24:26 EST 2005


Erik Max Francis <max at alcyone.com> wrote:
> Ben Finney wrote:
> > If I want to implement a __repr__ that's reasonably "nice" to the
> > programmer, what's the Right Way? Are there recipes I should look
> > at?
> 
> I tend to use:
> 
>      def __repr__(self):
>          if hasattr(self, '__str__'):
>              return '<%s @ 0x%x (%s)>' % (self.__class__.__name__,
>                                           id(self), str(self))
>          else:
>              return '<%s @ 0x%x>' % (self.__class__.__name__, id(self))

Well that just begs the question: what's a good way (or a Right Way,
if that exists) to write a __str__ for a complex class?

> If it's a relatively straightforward class where the entire state is
> exposed through the constructor, then a friendly repr is possible.
> Otherwise, it's not, and trying to otherwise do so may just be
> confusing.

"A friendly __repr__" doesn't necessarily mean outputting the full
syntax of a hypothetical constructor for the instance. I'm looking for
ways that people use to have __repr__ communicate things the
programmer will actually want to know, rather than only the qualified
class name and an arbitrary memory address.

It could be done just by hacking __repr__ with whatever things seem
appropriate, in some ad-hoc format. Or, as I'm hoping with this
thread, there may be common practices for outputting object state from
__repr__ that are concise yet easily standardised and/or recognised.

An idempotent __repr__ output seem to be the ideal, but as you say,
there are many classes for which it's impossible. What to do in those
cases? What's the Right Way? What's the common way?

-- 
 \            "There was a point to this story, but it has temporarily |
  `\                 escaped the chronicler's mind."  -- Douglas Adams |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list