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

Skip to content

Commit b5a40d4

Browse files
committed
Fix minor subclassing issue with collections.Counter
2 parents 8437fe2 + 6c9e5b7 commit b5a40d4

3 files changed

Lines changed: 13 additions & 2 deletions

File tree

Lib/collections/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -565,8 +565,8 @@ def subtract(self, iterable=None, **kwds):
565565
self.subtract(kwds)
566566

567567
def copy(self):
568-
'Like dict.copy() but returns a Counter instance instead of a dict.'
569-
return Counter(self)
568+
'Return a shallow copy.'
569+
return self.__class__(self)
570570

571571
def __reduce__(self):
572572
return self.__class__, (dict(self),)

Lib/test/test_collections.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -870,6 +870,15 @@ def test_copying(self):
870870
self.assertEqual(len(dup), len(words))
871871
self.assertEqual(type(dup), type(words))
872872

873+
def test_copy_subclass(self):
874+
class MyCounter(Counter):
875+
pass
876+
c = MyCounter('slartibartfast')
877+
d = c.copy()
878+
self.assertEqual(d, c)
879+
self.assertEqual(len(d), len(c))
880+
self.assertEqual(type(d), type(c))
881+
873882
def test_conversions(self):
874883
# Convert to: set, list, dict
875884
s = 'she sells sea shells by the sea shore'

Misc/NEWS

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,8 @@ Library
113113
- Issue #11467: Fix urlparse behavior when handling urls which contains scheme
114114
specific part only digits. Patch by Santoso Wijaya.
115115

116+
- collections.Counter().copy() now works correctly for subclasses.
117+
116118
- Issue #11474: Fix the bug with url2pathname() handling of '/C|/' on Windows.
117119
Patch by Santoso Wijaya.
118120

0 commit comments

Comments
 (0)