Rich __repr__

Donn Cave donn at
Thu Nov 3 01:41:43 CET 2005

In article <dk8tfa$1r9$1 at rose.polar.local>,
 Ben Finney <bignose+hates-spam at> wrote:

> Erik Max Francis <max at> 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?

Well, in my opinion there pretty much isn't a good way.  That is,
for any randomly selected complex class, there probably is no
worthwhile string value, hence no good __str__.

This dives off into a certain amount of controversy over what
repr and str are ideally supposed to do, but I think everyone
would agree that if there's an "represent object for programmer"
string value, it's the repr.  So the str is presumably not for
the programmer, but rather for the application, and I'm just
saying that for application purposes, not all objects can usefully
be reduced to a string value.

Meanwhile, the code above also raises some questions where str
is already provided.  Run it on your subclass-of-str object and
give the object a value of ') hi ('.  This is why containers
use repr to render their contents, not str.

> 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.

I guess the best I could suggest is to stick with the format
already used by instances (<__main__.C instance at 0x71eb8>)
and augment it with class-specific information.

     def make_repr(self, special):
         return '<%s instance at 0x%x: %s>' % (self.__class__.__name__,
                     id(self), special)
     def __repr__(self):
         return self.make_repr(repr(self.my_favorite_things))

This omits the module qualifier for the class name, but
arguably that's a bit of a nuisance anyway.  If there's a
best, common practice way to do it, I wouldn't care to pose
as an expert in such things, so you have to decide for yourself.

   Donn Cave, donn at

More information about the Python-list mailing list