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

Nick Coghlan ncoghlan at gmail.com
Sun Sep 14 23:56:17 CEST 2014


On 15 Sep 2014 05:09, "Chris Angelico" <rosuav at gmail.com> wrote:
>
> 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".

More generally, this is the kind of situation where we're more likely to
provide better tools for *writing* these kinds of representations, rather
than providing them by default (the latter approach is too likely to go
wrong).

There are currently two such key plumbing modules:

pprint: https://docs.python.org/3/library/pprint.html
reprlib: https://docs.python.org/3/library/reprlib.html

Redesigning the way pprint works to make it easier to customise is what
Łukasz had in mind when writing PEP 443 to add functools.singledispatch to
Python 3.4. It also makes it easier to write your own pretty printers and
custom repr functions that fall back to object introspection to provide
more details.

reprlib is currently focused on providing object representations that
aren't overwhelmingly long, even for large (or recursively nested)
containers. However, I seem to recall also seeing proposals on the tracker
to adding functions there that make it easier to emit named tuple style
representations for objects.

More generally, the idea of a "functionally equivalent named tuple" is also
relevant to implementing hashing, equality comparisons and ordering
operations in a sensible way, so there's actually potential here for a
third party module dedicated specifically to making it easier to write
classes that behave that way.

Regards,
Nick.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20140915/4a0e3fac/attachment-0001.html>


More information about the Python-ideas mailing list