Rich __repr__

Ben Finney bignose+hates-spam at
Mon Oct 31 08:32:34 CET 2005

Ben Finney <bignose+hates-spam at> 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
    >>> isinstance(m, basestring)
    >>> print m

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

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

        def __init__(self, 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