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

index bb6b15dbcc46bc9b0eae1111aba67d9d776e5723..cb720ac9abb7002e0543d53aec07bf5f33e6e8d3 100644 (file)
@@ -516,8 +516,8 @@ class Counter(dict):
             self.subtract(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 f6a43fcb1fc537f881f3820f1a276c8d22157682..8bdeb3d8f1f9b883fa5597fe084a29cc37ee4f82 100644 (file)
@@ -689,6 +689,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 3f75b1e9a3a43ba6908554a91d3a2d22a2c18a75..ed28d31e510ccf2116f33593cda5ad975c887532 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.