[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Pretty printing dicts with compact=True


> To me it also seems to be the most sensible behaviour, since
> dictionaries with their keys and values are different from most other
> sequences.
You've got a point but

1. That goes against the compact=True expected behaviour

2. Small dicts (e.g. /{x: x for x in range(5)}/) are still printed on a 
single line (regardless of the compact parameter), so I don't believe 
that was the rationale behind this behaviour.


On 9/11/18 1:05 PM, Max Zettlmei?l wrote:
> On Tue, Sep 11, 2018 at 1:58 PM, Nicolas Hug <niourf at gmail.com> wrote:
>> pprint({x: x for x in range(15)}, compact=True)
>>
>> would be be printed in 15 lines while it could fit on 2.
>>
>>
>> Is this a bug or was this decided on purpose?
> It is on purpose as can be seen in the code for pprint [1], which
> calls _format [2], which in the case of a dictionary calls
> _pprint_dict [3], which ultimately calls _format_dict_items [4].
> (which does not use compact or rather _compact)
>
> To me it also seems to be the most sensible behaviour, since
> dictionaries with their keys and values are different from most other
> sequences. In a dictionary the relation between keys and values is the
> most important one and reading a dictionary certainly is easier if
> each key value pair has a line of it's own. (Especially if the keys
> and values vary a lot in their lengths.)
>
> [1] https://github.com/python/cpython/blob/e42b705188271da108de42b55d9344642170aa2b/Lib/pprint.py#L138
> [2] https://github.com/python/cpython/blob/e42b705188271da108de42b55d9344642170aa2b/Lib/pprint.py#L154
> [3] https://github.com/python/cpython/blob/e42b705188271da108de42b55d9344642170aa2b/Lib/pprint.py#L180
> [4] https://github.com/python/cpython/blob/e42b705188271da108de42b55d9344642170aa2b/Lib/pprint.py#L333