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

Skip to content

Commit 1c746c2

Browse files
committed
Fix minor subclassing issue with collections.Counter
1 parent 181810b commit 1c746c2

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
@@ -459,8 +459,8 @@ def update(self, iterable=None, **kwds):
459459
self.update(kwds)
460460

461461
def copy(self):
462-
'Like dict.copy() but returns a Counter instance instead of a dict.'
463-
return Counter(self)
462+
'Return a shallow copy.'
463+
return self.__class__(self)
464464

465465
def __reduce__(self):
466466
return self.__class__, (dict(self),)

Lib/test/test_collections.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -680,6 +680,15 @@ def test_copying(self):
680680
self.assertEqual(len(dup), len(words))
681681
self.assertEqual(type(dup), type(words))
682682

683+
def test_copy_subclass(self):
684+
class MyCounter(Counter):
685+
pass
686+
c = MyCounter('slartibartfast')
687+
d = c.copy()
688+
self.assertEqual(d, c)
689+
self.assertEqual(len(d), len(c))
690+
self.assertEqual(type(d), type(c))
691+
683692
def test_conversions(self):
684693
# Convert to: set, list, dict
685694
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
@@ -58,6 +58,8 @@ Library
5858
- Issue #11467: Fix urlparse behavior when handling urls which contains scheme
5959
specific part only digits. Patch by Santoso Wijaya.
6060

61+
- collections.Counter().copy() now works correctly for subclasses.
62+
6163
- Issue #11474: Fix the bug with url2pathname() handling of '/C|/' on Windows.
6264
Patch by Santoso Wijaya.
6365

0 commit comments

Comments
 (0)