]> granicus.if.org Git - python/commitdiff
Fix minor subclassing issue with collections.Counter
authorRaymond Hettinger <python@rcn.com>
Fri, 15 Apr 2011 20:16:46 +0000 (13:16 -0700)
committerRaymond Hettinger <python@rcn.com>
Fri, 15 Apr 2011 20:16:46 +0000 (13:16 -0700)
Lib/collections.py
Lib/test/test_collections.py
Misc/NEWS

index 27bb5e126855dd695598ef11b8917d6433168262..30301ce89f64252735b3b4bc0e5e871d9bc49fe4 100644 (file)
@@ -459,8 +459,8 @@ class Counter(dict):
             self.update(kwds)
 
     def copy(self):
-        'Like dict.copy() but returns a Counter instance instead of a dict.'
-        return Counter(self)
+        'Return a shallow copy.'
+        return self.__class__(self)
 
     def __reduce__(self):
         return self.__class__, (dict(self),)
index 8989ac35c80ec006e2c76ba59f557a121a6db5b8..3d6ad091707974558a0b13aaaf93950b119517da 100644 (file)
@@ -680,6 +680,15 @@ class TestCounter(unittest.TestCase):
             self.assertEqual(len(dup), len(words))
             self.assertEqual(type(dup), type(words))
 
+    def test_copy_subclass(self):
+        class MyCounter(Counter):
+            pass
+        c = MyCounter('slartibartfast')
+        d = c.copy()
+        self.assertEqual(d, c)
+        self.assertEqual(len(d), len(c))
+        self.assertEqual(type(d), type(c))
+
     def test_conversions(self):
         # Convert to: set, list, dict
         s = 'she sells sea shells by the sea shore'
index 7ea8850328a052fc69c2548293404fdea158a37c..c424e1eb94bea9ccb96ea2b959b900bb6dd80407 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -58,6 +58,8 @@ Library
 - Issue #11467: Fix urlparse behavior when handling urls which contains scheme
   specific part only digits. Patch by Santoso Wijaya.
 
+- collections.Counter().copy() now works correctly for subclasses.
+
 - Issue #11474: Fix the bug with url2pathname() handling of '/C|/' on Windows.
   Patch by Santoso Wijaya.