]> granicus.if.org Git - python/commitdiff
Improve Counter.__repr__() to not fail with unorderable values
authorRaymond Hettinger <python@rcn.com>
Sat, 5 Nov 2011 20:35:26 +0000 (13:35 -0700)
committerRaymond Hettinger <python@rcn.com>
Sat, 5 Nov 2011 20:35:26 +0000 (13:35 -0700)
Lib/collections.py
Lib/test/test_collections.py

index 2b6abd879fc939deacc88302d883dcfd6d20e699..d2625fe03e384359f08f3f1514036f3900722f59 100644 (file)
@@ -583,8 +583,12 @@ class Counter(dict):
     def __repr__(self):
         if not self:
             return '%s()' % self.__class__.__name__
-        items = ', '.join(map('%r: %r'.__mod__, self.most_common()))
-        return '%s({%s})' % (self.__class__.__name__, items)
+        try:
+            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:
     #       Knuth TAOCP Volume II section 4.6.3 exercise 19
index ccf93c51c177910017636196aee7d3c89e56e305..8dc5559cae3aebef445fce6a7e1a930b0df02ae5 100644 (file)
@@ -893,6 +893,12 @@ class TestCounter(unittest.TestCase):
         c.subtract('aaaabbcce')
         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):
         # two paths, one for real dicts and one for other mappings
         elems = list('abracadabra')