[Python-ideas] Compact repr operator (i.e., __short_repr__)

Cory Benfield cory at lukasa.co.uk
Thu Feb 11 08:50:38 EST 2016


> On 11 Feb 2016, at 09:24, Mahmoud Hashemi <mahmoud at hatnote.com> wrote:
> 
> An enhanced repr allows developer-users to communicate the context of their usage so that the library authors can programmatically provide and prioritize information in their types. I've seen (and written) plenty of reprs that encode useful information in my types. To your example, I might have: <MyLock 0x123 held=True>.
> 

To be clear, I absolutely do that as well. In fact, if I’m writing a repr that’s almost always the form I give it.

Again, I’m not arguing that the repr isn’t useful. I’m arguing that it *is* useful, and that attempting to extend its utility with flags and complex functionality dilutes its utility. I’m in opposition to trying to shovel more into the repr: to try to extend it with more flexibility and therefore increase the burden on developers to be useful in that scenario.

I don’t disagree that the repr *can* be more: I just don’t think it should be. The repr is, like it or not, implicitly unstructured. Because the return value of __repr__ is a string, we cannot easily extend it for utility without pushing that cost out to developers. That is, if we wanted to support your “pretty=True” argument to repr(), all developers would need to start writing __repr__ functions that respond to that flag. This is, IMO, a bad way to obtain the feature you want, because at this point ‘pretty’ becomes constrained by the original author. It also means that some flags may not work if the author has not supported them: ‘pretty’ may do nothing, ‘pretty’ may work but ‘depth’ may be ignored, or ‘width’.

What I’ve understood from your mails is that you want is the ability to provide a *structured* debug representation of an object. That is, a function to hang off an object that is formatted according to the preferences of the user, not the developer. I think this is a good thing to have, because structured debug representations allow for more automated processing, as well as additional utility for users: see for example the structlog[0] module, which applies this concept to logging.

This is a good and reasonable thing to want, but it’s a different thing to the repr. The repr is fundamentally an unstructured representation of whatever the author believed was useful to describe about the object. I don’t see any reason to remove that or to put pressure on that mechanism to be more than it is.

Cory

[0]: https://structlog.readthedocs.org/en/stable/
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 801 bytes
Desc: Message signed with OpenPGP using GPGMail
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160211/21cc8155/attachment-0001.sig>


More information about the Python-ideas mailing list