Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 4e6bf41

Browse files
committed
Improve Counter.__repr__() to not fail with unorderable values
1 parent 0115fae commit 4e6bf41

2 files changed

Lines changed: 12 additions & 2 deletions

File tree

Lib/collections.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -583,8 +583,12 @@ def __delitem__(self, elem):
583583
def __repr__(self):
584584
if not self:
585585
return '%s()' % self.__class__.__name__
586-
items = ', '.join(map('%r: %r'.__mod__, self.most_common()))
587-
return '%s({%s})' % (self.__class__.__name__, items)
586+
try:
587+
items = ', '.join(map('%r: %r'.__mod__, self.most_common()))
588+
return '%s({%s})' % (self.__class__.__name__, items)
589+
except TypeError:
590+
# handle case where values are not orderable
591+
return '{0}({1!r})'.format(self.__class__.__name__, dict(self))
588592

589593
# Multiset-style mathematical operations discussed in:
590594
# Knuth TAOCP Volume II section 4.6.3 exercise 19

Lib/test/test_collections.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -893,6 +893,12 @@ def test_subtract(self):
893893
c.subtract('aaaabbcce')
894894
self.assertEqual(c, Counter(a=-1, b=0, c=-1, d=1, e=-1))
895895

896+
def test_repr_nonsortable(self):
897+
c = Counter(a=2, b=None)
898+
r = repr(c)
899+
self.assertIn("'a': 2", r)
900+
self.assertIn("'b': None", r)
901+
896902
def test_helper_function(self):
897903
# two paths, one for real dicts and one for other mappings
898904
elems = list('abracadabra')

0 commit comments

Comments
 (0)