Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Add frozendict support to _safe_repr()
  • Loading branch information
vstinner committed Feb 21, 2026
commit 9afd4bb6a892942d862d46a32a5a5a623346c349
20 changes: 16 additions & 4 deletions Lib/pprint.py
Original file line number Diff line number Diff line change
Expand Up @@ -637,12 +637,21 @@ def _safe_repr(self, object, context, maxlevels, level):
else:
return repr(object), True, False

if issubclass(typ, dict) and r is dict.__repr__:
if ((issubclass(typ, dict) and r is dict.__repr__)
or (issubclass(typ, frozendict) and r is frozendict.__repr__)):
is_frozendict = issubclass(typ, frozendict)
if not object:
return "{}", True, False
if is_frozendict:
rep = f"{object.__class__.__name__}()"
else:
rep = "{}"
return rep, True, False
objid = id(object)
if maxlevels and level >= maxlevels:
return "{...}", False, objid in context
rep = "{...}"
if is_frozendict:
rep = f"{object.__class__.__name__}({rep})"
return rep, False, objid in context
if objid in context:
return _recursion(object), False, True
context[objid] = 1
Expand All @@ -665,7 +674,10 @@ def _safe_repr(self, object, context, maxlevels, level):
if krecur or vrecur:
recursive = True
del context[objid]
return "{%s}" % ", ".join(components), readable, recursive
rep = "{%s}" % ", ".join(components)
if is_frozendict:
rep = f"{object.__class__.__name__}({rep})"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it covered by tests?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This line is coverted by test_basic_line_wrap() and test_same_as_repr() tests. If I modify the code to raise an exception, both tests fail.

return rep, readable, recursive

if (issubclass(typ, list) and r is list.__repr__) or \
(issubclass(typ, tuple) and r is tuple.__repr__):
Expand Down
Loading