Samuel Colvin writes:
Hi Steven,
Are you aware that dunder names are reserved for Python's use?
I wasn't aware it was explicitly discouraged, thanks for the link.
It seems to me that "__pretty__" (however it's implemented) seems a very sensible name for a method used when pretty printing objects. If it's one day implemented officially I think the approach I took is a good start, if it's not, then what I've done won't conflict with anything. :-)
That depends on whether somebody decides that "pretty" is a good name for a different function (such as going through all the strings in the object and making sure they are properly capitalized and use the same sentence-ending convention, or a different signature -- see below). Single leading underscore is reserved for class-private use, so you could more safely use "sunders" (_pretty_) or "splunders" (_pretty__). I'll note (as a mail geek) that use of a private method suffers a similar issue to that of the "X-" convention for message header field names: once standardized, you can't get rid of the old name. Nowadays, the recommendation in message header standardization community (*especially* for names that you are proposing for standardization) is to just go ahead and use an unprefixed name for private protocols. I don't know how close this analogy of the field name problem to the protocol implementation name problem is, but it's some evidence for your practice.
That's it. It's very simple but it allows effectively arbitrarily complex objects to be displayed. Especially since an object that wants to take care of all display of itself can just do so and return a string.
But that's precisely the issue with __pretty__: it allows objects to decide how to format themselves, when the application wants control. The way I think of pprint (FWIW, YMMV) is as a debug utility. If I were going to extend it, I would probably use a different name such as __debug_format__ for the dunder, and it would take the usual 'self' argument, plus hint arguments 'indent', 'width', 'height' describing the "subwindow" the caller wants to give it. The return value would be a (possibly nested) list of strings, each including the indent the object proposes to use. Then the simplest implementation of the pretty() function would simply flatten the nested list, join the result, and output it, while a very opinionated pretty() might strip all the indentation, apply its own opinion of the appropriate indentation, then truncate the indented line to its opinion of the appropriate length. Steve