Rich __repr__

Erik Max Francis max at alcyone.com
Tue Nov 1 02:15:18 EST 2005


Ben Finney wrote:

> The builtin types have __repr__ attributes that return something nice,
> that looks like the syntax one would use to create that particular
> instance.
> 
> The default __repr__ for custom classes show the fully-qualified class
> name, and the memory address of the instance.
> 
> 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))

The general problem here is that the syntax to create an instance may 
not (and usually is not, for complex classes) sufficient to recreate the 
entire state of an instance.  Mutable classes in general compound the 
problem, but examples like files and sockets underscore how it's really 
impossible to take a snapshot of a class and reproduce it later (even 
pickles can't handle these, of course).

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.

-- 
Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
   It is fatal to enter any war without the will to win it.
   -- Douglas MacArthur



More information about the Python-list mailing list