Rich __repr__

Ben Finney bignose+hates-spam at benfinney.id.au
Mon Oct 31 02:32:34 EST 2005


Ben Finney <bignose+hates-spam at benfinney.id.au> 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?

As a (carefully selected) example from the code I'm writing:


    >>> import lib.attribute
    >>> m = lib.attribute.Human_Sex("male")
    >>> m
    Human_Sex(name='male')
    >>> isinstance(m, basestring)
    True
    >>> print m
    male

Thus, a Human_Sex instance is a string, and that's how it prints
(because of the __str__ attribute of the 'str' type). But since there
are potentially other things to know about a Human_Sex instance, the
__repr__ is overridden to give an idealised constructor call for the
instance.

    class Human_Sex(str):
        def __repr__(self):
            repr_str = "%s(name=%s)" % (
                self.__class__.__name__,
                str.__repr__(self)
            )
            return repr_str

        def __init__(self, name):
            str.__init__(name)
            # [... other initialisation for this class ...]

I've simplified somewhat; Human_Sex is actually just one possible
attribute being implemented, and the above methods actually come from
a superclass. I'm looking for how to do this in general, and this is a
simple enough example of what I want.

Is this __repr__ implementation too complex? Too simple? Limited in
some way? Confusingly non-standard?

-- 
 \        "Laurie got offended that I used the word 'puke.' But to me, |
  `\              that's what her dinner tasted like."  -- Jack Handey |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list