[Python-ideas] __repr__: to support pprint

Steven D'Aprano steve at pearwood.info
Wed Mar 1 08:50:26 EST 2017


On Wed, Mar 01, 2017 at 01:04:00PM +1100, Chris Angelico wrote:
> On Wed, Mar 1, 2017 at 12:58 PM, Matthias welp <boekewurm at gmail.com> wrote:
> > You are free to experiment with overriding/extending __repr__ for your
> > internal usage, but please note that it might break external libraries
> > depending on obj.__repr__ or repr(obj), and print() might break when
> > using built-in types as containers for your objects.
> 
> Given that this started out with a post about pprint, maybe a more
> viable approach would be a dedicated __pprint__ hook? That might be
> easier to push through. (I'm not pushing for it though.)

I like the idea of a __pprint__ dunder method in principle.

But... what exactly is it supposed to do? In general, `self` cannot 
pretty-print itself, since it doesn't know if it is embedded inside 
another object, or whether the pretty-printer wants to constrain it to a 
certain width or number of lines.

For example, if the printer wants to display a list using (say) three 
columns, aligned at the decimal points:

[ 31.08713241722979,   983.3425750471824,      -7234.474117265795, 
   0.7563959975516478,  21.08150956898832,        98.85759870687133, 
 219.76826846350912,    -7.640051348488824,        0.5731518549129719, 
  32.961711789297816,    0.7563959975516478,  953487.1772710333       ]

how would each float know how many leading spaces to use to align with 
the rest of the column? I don't think it could. Only the pretty printer 
itself would know how to align the float reprs, whether to truncate the 
displays, etc.

It is possible that we could come up with a pretty-printing protocol, 
but that wouldn't be a trivial job.


-- 
Steve


More information about the Python-ideas mailing list