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

Skip to content

Commit 6c9e5b7

Browse files
committed
Fix minor subclassing issue with collections.Counter
2 parents 8881868 + 1c746c2 commit 6c9e5b7

3 files changed

Lines changed: 13 additions & 2 deletions

File tree

Lib/collections.py

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

538538
def copy(self):
539-
'Like dict.copy() but returns a Counter instance instead of a dict.'
540-
return Counter(self)
539+
'Return a shallow copy.'
540+
return self.__class__(self)
541541

542542
def __reduce__(self):
543543
return self.__class__, (dict(self),)

Lib/test/test_collections.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -812,6 +812,15 @@ def test_copying(self):
812812
self.assertEqual(len(dup), len(words))
813813
self.assertEqual(type(dup), type(words))
814814

815+
def test_copy_subclass(self):
816+
class MyCounter(Counter):
817+
pass
818+
c = MyCounter('slartibartfast')
819+
d = c.copy()
820+
self.assertEqual(d, c)
821+
self.assertEqual(len(d), len(c))
822+
self.assertEqual(type(d), type(c))
823+
815824
def test_conversions(self):
816825
# Convert to: set, list, dict
817826
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
@@ -63,6 +63,8 @@ Library
6363
- Issue #11467: Fix urlparse behavior when handling urls which contains scheme
6464
specific part only digits. Patch by Santoso Wijaya.
6565

66+
- collections.Counter().copy() now works correctly for subclasses.
67+
6668
- Issue #11474: Fix the bug with url2pathname() handling of '/C|/' on Windows.
6769
Patch by Santoso Wijaya.
6870

0 commit comments

Comments
 (0)