Skip to content

Commit b1df0bb

Browse files
committed
Implement expand=True for dict views
1 parent 64238cd commit b1df0bb

File tree

2 files changed

+53
-8
lines changed

2 files changed

+53
-8
lines changed

Lib/pprint.py

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -321,19 +321,21 @@ def _pprint_dict_view(self, object, stream, indent, allowance, context, level):
321321
key = _safe_tuple
322322
else:
323323
key = _safe_key
324+
324325
write = stream.write
325-
write(object.__class__.__name__ + '([')
326-
if self._indent_per_level > 1:
327-
write((self._indent_per_level - 1) * ' ')
328-
length = len(object)
329-
if length:
326+
write(
327+
self._format_block_start(object.__class__.__name__ + "([", indent)
328+
)
329+
330+
if len(object):
330331
if self._sort_dicts:
331332
entries = sorted(object, key=key)
332333
else:
333334
entries = object
334-
self._format_items(entries, stream, indent, allowance + 1,
335-
context, level)
336-
write('])')
335+
self._format_items(
336+
entries, stream, indent, allowance + 2, context, level
337+
)
338+
write(self._format_block_end("])", indent))
337339

338340
def _pprint_mapping_abc_view(self, object, stream, indent, allowance, context, level):
339341
"""Pretty print mapping views from collections.abc."""

Lib/test/test_pprint.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1903,6 +1903,49 @@ def __init__(self, *args, **kwargs):
19031903
]""")
19041904

19051905

1906+
def test_expand_dict_keys(self):
1907+
d = {"foo": 1, "bar": 2, "baz": 3, "qux": 4, "quux": 5}
1908+
self.assertEqual(
1909+
pprint.pformat(d.keys(), width=20, indent=4, expand=True),
1910+
"""\
1911+
dict_keys([
1912+
'bar',
1913+
'baz',
1914+
'foo',
1915+
'quux',
1916+
'qux'
1917+
])""",
1918+
)
1919+
1920+
def test_expand_dict_values(self):
1921+
d = {"foo": 1, "bar": 2, "baz": 3, "qux": 4, "quux": 5}
1922+
self.assertEqual(
1923+
pprint.pformat(d.values(), width=20, indent=4, expand=True),
1924+
"""\
1925+
dict_values([
1926+
1,
1927+
2,
1928+
3,
1929+
4,
1930+
5
1931+
])""",
1932+
)
1933+
1934+
def test_expand_dict_items(self):
1935+
d = {"foo": 1, "bar": 2, "baz": 3, "qux": 4, "quux": 5}
1936+
self.assertEqual(
1937+
pprint.pformat(d.items(), width=20, indent=4, expand=True),
1938+
"""\
1939+
dict_items([
1940+
('bar', 2),
1941+
('baz', 3),
1942+
('foo', 1),
1943+
('quux', 5),
1944+
('qux', 4)
1945+
])""",
1946+
)
1947+
1948+
19061949
class DottedPrettyPrinter(pprint.PrettyPrinter):
19071950

19081951
def format(self, object, context, maxlevels, level):

0 commit comments

Comments
 (0)