On 7/22/20 1:31 PM, Stavros Macrakis wrote:
I see how to limit the *depth* in pretty-printing:
import pprint
pprint.PrettyPrinter(depth=2).pprint(((11,12,13),(21,22,23,(241,242,243),25,26,27)))
((11, 12, 13),
(21, 22, 23, (...), 25, 26, 27))
But I would also like to limit the *length, *something like this:
pprint.PrettyPrinter(depth=2,length=4
).pprint(((11,12,13),(21,22,23,(241,242,243),25,26,27)))
((11, 12, 13),
(21, 22, 23, (...), ...)) # Only show first 4 elements
How can I do that?
That's 'a bit of an ask' given that the four elements could be of any
data-type (object)! Secondly, I'm having difficulty working-out how you
wish to define "element".
1 Limit the input:
If you know the input, in the example it is nested tuple, then it would
be trivial to slice the collection *before* passing to pprint, eg
t = ( 1, 2, 3, 4 )
t[ :2 ]
(1, 2)
pprint.pprint( t[ :2 ] )
(1, 2)
However, if the second element were an embedded collection, then that
idea suffers a similar short-coming to the existing depth parameter!
1a
That said, if you also know the hierarchy, you could get really clever
with a recursive function which 'pops' the first element from any given
hierarchical construct, to the required number of elements. Sounds like
a 'fun' (ie dastardly) project to assign coding trainees!
(this list doesn't accept graphic attachments otherwise I'd demonstrate
my vicious grin...)
PS should you try this, would welcome a copy (off-list).
2 Limit the output:
Remember that the signature is:
class pprint.PrettyPrinter(indent=1, width=80, depth=None,
stream=None, *, compact=False,
sort_dicts=True)
How about capturing the stream output? Could you then post-process that
by counting commas!
NB I have never tried capturing the stream o/p!
- or if you really want to 'go nuts', dust-off your polish notation and
count opening and closing parentheses as well...
2a
One has to wonder though, why not grab the output stream and print only
the first n-characters? (on the grounds that 'close-enough is
good-enough'. However, it's your spec...)
--
Regards =dn
--
https://mail.python.org/mailman/listinfo/python-list