I thought about this a great deal when building the devtools package: https://pypi.org/project/devtools/

It prints common types in a pretty way (with the file, line number and value or expression that was printed):

image.png

But it also looks for a "__pretty__" method on objects, and if found uses that to display the object.

I haven't yet documented that properly, but it's already implemented in pydantic (which I also maintain) so pydantic models can be displayed in a prettier way:

image.png

The challenge here is that "__pretty__" can't just return a string as that leaves all the formatting up to that method, rather than the printing/display library. So devtools expects "__pretty__" to yield objects in name, value pairs (or just values for list like objects), devtools then takes care of recursively displaying the values next to each name. Long term if an approach like this was more widely adopted, this approach should work well for things like IDEs which may want to display this data within a custom UI.

I'll try and document the "__pretty__" generate when I get a chance, but if anyone has more questions, feel free to create an issue at https://github.com/samuelcolvin/python-devtools or ask here.

Samuel

--

Samuel Colvin