Using __repr__ or __str__ for own printable class?

Donn Cave donn at drizzle.com
Thu Apr 24 06:27:09 CEST 2003


Quoth David Abrahams <dave at boost-consulting.com>:
| "Donn Cave" <donn at drizzle.com> writes:
[... re class whose __repr__ can break on bad data ...]
|> So here's this object.  You can't repr() it, including implicitly
|> from the interpreter prompt - you get a traceback instead.  Of course
|> that also goes for the list object that contains this object.  To
|> me, this is not right, and maybe it ought to be another point to
|> consider if we're reconsidering the documentation for __repr__.
|> Wish I could specify this better, but I believe there's a minimalist
|> way to think about implementing __repr__ that will tend to make it
|> less interesting but more reliable.
|
| One idea might be:
|
|     # pseudocode
|     class object:
|          def __repr__(self):
|             if hasattr(self, '__getinitargs__'):
|                 return (
|                     repr(self.__class__)
|                   + repr(self.__getinitargs__())
|                 )
|             else:
|                 return # whatever we do today
|
| I know that would only handle a small class of types, since most
| aren't picklable, but it might encourage people to implement
| __getinitargs__ to get the right __repr__ behavior.

If you haven't been following this thread, note that it isn't
clear to everyone that this would always be the right behavior
even when it's possible.  Not saying there's any problem with
this implementation, but just to draw a fine point, not necessarily
"the right" behavior.

	Donn Cave, donn at drizzle.com




More information about the Python-list mailing list