[Python-ideas] Bring namedtuple's __str__ and __repr__ behavior to regular classes

Chris Angelico rosuav at gmail.com
Sun Sep 14 21:08:50 CEST 2014


By the way:

On Mon, Sep 15, 2014 at 4:48 AM, John Wong <gokoproject at gmail.com> wrote:
> The main challenge:
>
> Where and how do we actually look for what attributes are relevant?
> namedtuple can do it because it has __slot__ and we know in advance how many
> attributes are set. In regular class, we deal with dynamic attribute
> setting, single and inheritances. I don't have an answer for this simply
> because I lack of experience. We can certainly start with the attributes set
> in the main instance and one level up in the inheritance chain.

This is a fundamentally hard problem. Obviously it's easy to see what
attributes are set, but figuring out which are relevant is usually a
job for the class itself. So what you might want to do is have a class
attribute, and then have your custom __repr__ scan through all of
__bases__, collecting up these "important attributes". Something like
this:

class Point2D(object):
    show_in_repr = "x", "y"
    ...

class Point3D(Point2D):
    show_in_repr = "z"
    ...

Then the repr for object could follow the chain, pick up all the
show_in_repr class attributes, and even use that for the order
(parents first, in inheritance order, then this class's attributes).
But at this point, you're definitely in the realm of custom code, not
changes to the language. Which is good, because you'll likely change
your mind about the details, and it's easy to recode your top-level
inherit :)

ChrisA


More information about the Python-ideas mailing list