8000 gh-90117: handle dict and mapping views in pprint by devdanzin · Pull Request #30135 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content

gh-90117: handle dict and mapping views in pprint #30135

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 45 commits into from
May 20, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
45 commits
Select commit Hold shift + click to select a range
f7835ca
Teach pprint about dict views with PrettyPrinter._pprint_dict_view an…
devdanzin Dec 16, 2021
1eda2d5
Merge branch 'main' of https://github.com/python/cpython into pprint_…
devdanzin Dec 17, 2021
9500a74
Use _private names for _dict_*_view attributes of PrettyPrinter.
devdanzin Dec 17, 2021
653cdea
Use explicit 'items' keyword when calling _pprint_dict_view from _ppr…
devdanzin Dec 18, 2021
884f224
📜🤖 Added by blurb_it.
blurb-it[bot] Dec 18, 2021
48be1e9
Properly indent code.
devdanzin Jan 19, 2022
9745491
WIP: Improve tests and make short views sortable.
devdanzin Jan 19, 2022
7edb29d
fix typo
merwok Apr 24, 2022
7d2fa0f
Merge branch 'main' into pprint_dict_view
merwok Apr 24, 2022
32773ce
Merge branch 'main' into pprint_dict_view
arhadthedev Mar 4, 2023
15dd266
Address the failing Docs check
arhadthedev Mar 4, 2023
6898bc4
Merge branch 'python:main' into pprint_dict_view
devdanzin Apr 6, 2024
67e3f14
Add tests for collections.abc.[Keys|Items|Mapping|Values]View support…
devdanzin Apr 7, 2024
65e0be2
Add support for collections.abc.[Keys|Items|Mapping|Values]View in pp…
devdanzin Apr 7, 2024
c91af09
Split _pprint_dict_view into _pprint_abc_view, so pretty-printing nor…
devdanzin Apr 7, 2024
5b2341c
Simplify redundant code.
devdanzin Apr 7, 2024
a9ff3df
Add collections.abc views to some existing pprint tests.
devdanzin Apr 7, 2024
4c67166
Remove TODO.
devdanzin Apr 7, 2024
bfa9868
Test that views from collection.UserDict are correctly formatted by p…
devdanzin Apr 7, 2024
148b469
Handle recursive dict and ABC views.
devdanzin Apr 7, 2024
34abce7
Test that subclasses of ABC views work in pprint.
devdanzin Apr 7, 2024
09839a6
Test dict views coming from collections.Counter.
devdanzin Apr 7, 2024
091c3bb
Test ABC views coming from collections.ChainMap.
devdanzin Apr 7, 2024
29655a0
Test odict views coming from collections.OrderedDict.
devdanzin Apr 7, 2024
7ecb456
Merge branch 'main' into pprint_dict_view
devdanzin Apr 8, 2024
646816a
Rename _pprint_abc_view to _pprint_mapping_abc_view.
devdanzin Apr 8, 2024
7537a52
Add pprint test for mapping ABC views where ._mapping has a custom __…
devdanzin Apr 9, 2024
7a6769d
When a mapping ABC view has a ._mapping that defines a custom __repr_…
devdanzin Apr 9, 2024
7dcb9cf
Merge branch 'python:main' into pprint_dict_view
devdanzin Apr 9, 2024
06babe4
Merge remote-tracking branch 'refs/remotes/origin/pprint_dict_view' i…
devdanzin Apr 9, 2024
58692d2
Add tests for ABC mapping views subclasses that don't replace __repr_…
devdanzin Apr 21, 2024
8e605c1
Simplify the pretty printing of ABC mapping views.
devdanzin Apr 21, 2024
7e27e02
Merge branch 'python:main' into pprint_dict_view
devdanzin Apr 21, 2024
eb66934
Merge remote-tracking branch 'refs/remotes/origin/pprint_dict_view' i…
devdanzin Apr 21, 2024
1dc4ab2
Add a test for depth handling when pretty printing dict views.
devdanzin Apr 21, 2024
f267452
Fix checking whether the view type is a subclass of an items view, ad…
devdanzin Apr 22, 2024
3867338
Move construction of the views __repr__ set out of _safe_repr.
devdanzin Apr 26, 2024
1a609d0
Merge branch 'main' into pprint_dict_view
devdanzin Apr 26, 2024
bca6f6f
Merge remote-tracking branch 'refs/remotes/origin/pprint_dict_view' i…
devdanzin Apr 26, 2024
d020f86
Merge branch 'python:main' into pprint_dict_view
devdanzin May 21, 2024
ee7b521
Merge branch 'python:main' into pprint_dict_view
devdanzin May 30, 2024
7009887
Merge branch 'python:main' into pprint_dict_view
devdanzin Jul 1, 2024
9499115
Merge branch 'main' into pprint_dict_view
devdanzin Oct 29, 2024
692c0cd
Merge branch 'main' into pprint_dict_view
AA-Turner Apr 20, 2025
90e069c
Merge branch 'main' into pprint_dict_view
gpshead May 20, 2025
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
79 changes: 79 additions & 0 deletions Lib/pprint.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,49 @@ def _pprint_ordered_dict(self, object, stream, indent, allowance, context, level

_dispatch[_collections.OrderedDict.__repr__] = _pprint_ordered_dict

def _pprint_dict_view(self, object, stream, indent, allowance, context, level):
"""Pretty print dict views (keys, values, items)."""
if isinstance(object, self._dict_items_view):
key = _safe_tuple
else:
key = _safe_key
write = stream.write
write(object.__class__.__name__ + '([')
if self._indent_per_level > 1:
write((self._indent_per_level - 1) * ' ')
length = len(object)
if length:
if self._sort_dicts:
entries = sorted(object, key=key)
else:
entries = object
self._format_items(entries, stream, indent, allowance + 1,
context, level)
write('])')

def _pprint_mapping_abc_view(self, object, stream, indent, allowance, context, level):
"""Pretty print mapping views from collections.abc."""
write = stream.write
write(object.__class__.__name__ + '(')
# Dispatch formatting to the view's _mapping
self._format(object._mapping, stream, indent, allowance, context, level)
write(')')

_dict_keys_view = type({}.keys())
_dispatch[_dict_keys_view.__repr__] = _pprint_dict_view

_dict_values_view = type({}.values())
_dispatch[_dict_values_view.__repr__] = _pprint_dict_view

_dict_items_view = type({}.items())
_dispatch[_dict_items_view.__repr__] = _pprint_dict_view

_dispatch[_collections.abc.MappingView.__repr__] = _pprint_mapping_abc_view

_view_reprs = {cls.__repr__ for cls in
(_dict_keys_view, _dict_values_view, _dict_items_view,
_collections.abc.MappingView)}

def _pprint_list(self, object, stream, indent, allowance, context, level):
stream.write('[')
self._format_items(object, stream, indent, allowance + 1,
Expand Down Expand Up @@ -610,6 +653,42 @@ def _safe_repr(self, object, context, maxlevels, level):
del context[objid]
return "{%s}" % ", ".join(components), readable, recursive

if issubclass(typ, _collections.abc.MappingView) and r in self._view_reprs:
objid = id(object)
if maxlevels and level >= maxlevels:
return "{...}", False, objid in context
if objid in context:
return _recursion(object), False, True
key = _safe_key
if issubclass(typ, (self._dict_items_view, _collections.abc.ItemsView)):
key = _safe_tuple
if hasattr(object, "_mapping"):
# Dispatch formatting to the view's _mapping
mapping_repr, readable, recursive = self.format(
object._mapping, context, maxlevels, level)
return (typ.__name__ + '(%s)' % mapping_repr), readable, recursive
elif hasattr(typ, "_mapping"):
# We have a view that somehow has lost its type's _mapping, raise
# an error by calling repr() instead of failing cryptically later
return repr(object), True, False
if self._sort_dicts:
object = sorted(object, key=key)
context[objid] = 1
readable = True
recursive = False
components = []
append = components.append
level += 1
for val in object:
vrepr, vreadable, vrecur = self.format(
val, context, maxlevels, level)
append(vrepr)
readable = readable and vreadable
if vrecur:
recursive = True
del context[objid]
return typ.__name__ + '([%s])' % ", ".join(components), readable, recursive

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