Skip to content

Commit 64238cd

Browse files
committed
Implement expand=True for frozendict
1 parent c6a6c1a commit 64238cd

2 files changed

Lines changed: 34 additions & 8 deletions

File tree

Lib/pprint.py

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -274,14 +274,26 @@ def _pprint_dict(self, object, stream, indent, allowance, context, level):
274274
def _pprint_frozendict(self, object, stream, indent, allowance, context, level):
275275
write = stream.write
276276
cls = object.__class__
277-
write(cls.__name__ + '(')
278-
length = len(object)
279-
if length:
280-
self._pprint_dict(object, stream,
281-
indent + len(cls.__name__) + 1,
282-
allowance + 1,
283-
context, level)
284-
write(')')
277+
if not len(object):
278+
write(repr(object))
279+
return
280+
281+
write(self._format_block_start(cls.__name__ + "({", indent))
282+
self._write_indent_padding(write)
283+
284+
if self._sort_dicts:
285+
items = sorted(object.items(), key=_safe_tuple)
286+
else:
287+
items = object.items()
288+
self._format_dict_items(
289+
items,
290+
stream,
291+
self._child_indent(indent, len(cls.__name__) + 1),
292+
allowance + 2,
293+
context,
294+
level,
295+
)
296+
write(self._format_block_end("})", indent))
285297

286298
_dispatch[frozendict.__repr__] = _pprint_frozendict
287299

Lib/test/test_pprint.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1664,6 +1664,20 @@ def test_expand_frozenset(self):
16641664
(1, 2, 3)
16651665
})""")
16661666

1667+
def test_expand_frozendict(self):
1668+
dummy_frozendict = frozendict(
1669+
{"foo": "bar", "baz": 123, "qux": [1, 2]}
1670+
)
1671+
self.assertEqual(
1672+
pprint.pformat(dummy_frozendict, width=20, indent=4, expand=True),
1673+
"""\
1674+
frozendict({
1675+
'baz': 123,
1676+
'foo': 'bar',
1677+
'qux': [1, 2]
1678+
})""",
1679+
)
1680+
16671681
def test_expand_bytes(self):
16681682
dummy_bytes = b"Hello world! foo bar baz 123 456 789"
16691683
self.assertEqual(pprint.pformat(dummy_bytes, width=20, indent=4,

0 commit comments

Comments
 (0)