Skip to content

Commit d6da90f

Browse files
committed
Issues #10017 and #14998: Fix TypeError using pprint on dictionaries with unorderable key.
1 parent b4bbee2 commit d6da90f

File tree

3 files changed

+17
-1
lines changed

3 files changed

+17
-1
lines changed

Lib/pprint.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,11 @@ def __init__(self, obj):
8686
self.obj = obj
8787

8888
def __lt__(self, other):
89-
rv = self.obj.__lt__(other.obj)
89+
try:
90+
rv = self.obj.__lt__(other.obj)
91+
except TypeError:
92+
rv = NotImplemented
93+
9094
if rv is NotImplemented:
9195
rv = (str(type(self.obj)), id(self.obj)) < \
9296
(str(type(other.obj)), id(other.obj))

Lib/test/test_pprint.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -462,6 +462,15 @@ def test_sort_unorderable_values(self):
462462
self.assertEqual(clean(pprint.pformat(dict.fromkeys(keys))),
463463
'{' + ','.join('%r:None' % k for k in skeys) + '}')
464464

465+
# Issue 10017: TypeError on user-defined types as dict keys.
466+
self.assertEqual(pprint.pformat({Unorderable: 0, 1: 0}),
467+
'{1: 0, ' + repr(Unorderable) +': 0}')
468+
469+
# Issue 14998: TypeError on tuples with NoneTypes as dict keys.
470+
self.assertEqual(pprint.pformat({(1,): 0, (None,): 0}),
471+
'{(1,): 0, (None,): 0}')
472+
473+
465474
class DottedPrettyPrinter(pprint.PrettyPrinter):
466475

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

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,9 @@ Core and Builtins
9898
Library
9999
-------
100100

101+
- Issues #10017 and #14998: Fix TypeError using pprint on dictionaries with
102+
user-defined types as keys or other unorderable keys.
103+
101104
- Issue #14635: telnetlib will use poll() rather than select() when possible
102105
to avoid failing due to the select() file descriptor limit.
103106

0 commit comments

Comments
 (0)