Skip to content

Commit 87eb482

Browse files
Issue #23502: The pprint module now supports mapping proxies.
In particular the __dict__ attributes of building types.
1 parent 022f203 commit 87eb482

File tree

3 files changed

+40
-0
lines changed

3 files changed

+40
-0
lines changed

Lib/pprint.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636

3737
import re
3838
import sys as _sys
39+
import types as _types
3940
from collections import OrderedDict as _OrderedDict
4041
from io import StringIO as _StringIO
4142

@@ -313,6 +314,14 @@ def _pprint_bytearray(self, object, stream, indent, allowance, context, level):
313314

314315
_dispatch[bytearray.__repr__] = _pprint_bytearray
315316

317+
def _pprint_mappingproxy(self, object, stream, indent, allowance, context, level):
318+
stream.write('mappingproxy(')
319+
self._format(object.copy(), stream, indent + 13, allowance + 1,
320+
context, level)
321+
stream.write(')')
322+
323+
_dispatch[_types.MappingProxyType.__repr__] = _pprint_mappingproxy
324+
316325
def _format_dict_items(self, items, stream, indent, allowance, context,
317326
level):
318327
write = stream.write

Lib/test/test_pprint.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import random
88
import collections
99
import itertools
10+
import types
1011

1112
# list, tuple and dict subclasses that do or don't overwrite __repr__
1213
class list2(list):
@@ -271,6 +272,34 @@ def test_ordered_dict(self):
271272
'a': 6,
272273
'lazy': 7,
273274
'dog': 8}""")
275+
276+
def test_mapping_proxy(self):
277+
words = 'the quick brown fox jumped over a lazy dog'.split()
278+
d = dict(zip(words, itertools.count()))
279+
m = types.MappingProxyType(d)
280+
self.assertEqual(pprint.pformat(m), """\
281+
mappingproxy({'a': 6,
282+
'brown': 2,
283+
'dog': 8,
284+
'fox': 3,
285+
'jumped': 4,
286+
'lazy': 7,
287+
'over': 5,
288+
'quick': 1,
289+
'the': 0})""")
290+
d = collections.OrderedDict(zip(words, itertools.count()))
291+
m = types.MappingProxyType(d)
292+
self.assertEqual(pprint.pformat(m), """\
293+
mappingproxy({'the': 0,
294+
'quick': 1,
295+
'brown': 2,
296+
'fox': 3,
297+
'jumped': 4,
298+
'over': 5,
299+
'a': 6,
300+
'lazy': 7,
301+
'dog': 8})""")
302+
274303
def test_subclassing(self):
275304
o = {'names with spaces': 'should be presented using repr()',
276305
'others.should.not.be': 'like.this'}

Misc/NEWS

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ Core and Builtins
2626
Library
2727
-------
2828

29+
- Issue #23502: The pprint module now supports mapping proxies.
30+
2931
- Issue #17530: pprint now wraps long bytes objects and bytearrays.
3032

3133
- Issue #22687: Fixed some corner cases in breaking words in tetxtwrap.

0 commit comments

Comments
 (0)