I'm trying to create an object with a bunch of dictionaries (example below):
class test(object):
def __init__(self):
self.test_dict1 = {}
self.test_dict2 = {}
...
I need to run a bunch of what-if scenarios that involve modifying those dictionaries and computing something based on them.
a = test()
for i in range(1000):
b = copy.deepcopy(a)
# do stuff to b and output result
...
However, most of the dictionary content will stay the same. I could just use copy.deepcopy()
but that is very slow because it has to make a copy of ALL of the dictionary content (it is very large), and b
will not b very different a
, so it would make sense to reference a
for the most part, and only override the keys for the items that are modified in b
.
Since the dictionaries don't contain any mutable elements (i.e. all integers or strings), using copy.copy()
on each individual dictionary should still work and will be significantly faster. However, since a
is a class object, this code will also modify a
:
# This code will modify a whenever b is modified
a = test()
for i in range(1000):
b = copy.copy(a)
# do stuff
...
How can I overload the __deepcopy__
function so that it only makes regular copies of objects? Also, as long as all of the dictionaries have immutable elements, am I correct in assuming this will work as intended (or is this not a good idea)?