I am writing custom classes that inherit either from the Python class dict
, or collections.Counter
and I am facing problem with the behaviour of deepcopy
. The problem is basically that deepcopy
works as intended when inheriting from dict
but not from Counter
.
Here is an example:
from copy import deepcopy
from collections import Counter
class MyCounter(Counter):
def __init__(self, foo):
self.foo = foo
class MyDict(dict):
def __init__(self, foo):
self.foo = foo
c = MyCounter(0)
assert c.foo == 0 # Success
c1 = deepcopy(c)
assert c1.foo == 0 # Failure
d = MyDict(0)
assert d.foo == 0 # Success
d1 = deepcopy(d)
assert d1.foo == 0 # Success
I am a bit clueless as to why this is happening given that the source code of the Counter
class does not seem to change anything about the deepcopy (no custom __deepcopy__
method for instance).
I understand that I may have to write a custom __deepcopy__
method but it's not clear to me how to. In general I would rather not have to do that given that it works perfectly for dict
.
Any help will be much appreciated.