Kaydet (Commit) 4e6bf419 authored tarafından Raymond Hettinger's avatar Raymond Hettinger

Improve Counter.__repr__() to not fail with unorderable values

üst 0115fae8
...@@ -583,8 +583,12 @@ class Counter(dict): ...@@ -583,8 +583,12 @@ class Counter(dict):
def __repr__(self): def __repr__(self):
if not self: if not self:
return '%s()' % self.__class__.__name__ return '%s()' % self.__class__.__name__
items = ', '.join(map('%r: %r'.__mod__, self.most_common())) try:
return '%s({%s})' % (self.__class__.__name__, items) items = ', '.join(map('%r: %r'.__mod__, self.most_common()))
return '%s({%s})' % (self.__class__.__name__, items)
except TypeError:
# handle case where values are not orderable
return '{0}({1!r})'.format(self.__class__.__name__, dict(self))
# Multiset-style mathematical operations discussed in: # Multiset-style mathematical operations discussed in:
# Knuth TAOCP Volume II section 4.6.3 exercise 19 # Knuth TAOCP Volume II section 4.6.3 exercise 19
......
...@@ -893,6 +893,12 @@ class TestCounter(unittest.TestCase): ...@@ -893,6 +893,12 @@ class TestCounter(unittest.TestCase):
c.subtract('aaaabbcce') c.subtract('aaaabbcce')
self.assertEqual(c, Counter(a=-1, b=0, c=-1, d=1, e=-1)) self.assertEqual(c, Counter(a=-1, b=0, c=-1, d=1, e=-1))
def test_repr_nonsortable(self):
c = Counter(a=2, b=None)
r = repr(c)
self.assertIn("'a': 2", r)
self.assertIn("'b': None", r)
def test_helper_function(self): def test_helper_function(self):
# two paths, one for real dicts and one for other mappings # two paths, one for real dicts and one for other mappings
elems = list('abracadabra') elems = list('abracadabra')
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment