I understand the difference between copy
vs. deepcopy
in the copy module. I've used copy.copy
and copy.deepcopy
before successfully, but this is the first time I've actually gone about overloading the __copy__
and __deepcopy__
methods. I've already Googled around and looked through the built-in Python modules to look for instances of the __copy__
and __deepcopy__
functions (e.g. sets.py
, decimal.py
, and fractions.py
), but I'm still not 100% sure I've got it right.
Here's my scenario:
I have a configuration object. Initially, I'm going to instantiate one configuration object with a default set of values. This configuration will be handed off to multiple other objects (to ensure all objects start with the same configuration). However, once user interaction starts, each object needs to tweak its configurations independently without affecting each other's configurations (which says to me I'll need to make deepcopys of my initial configuration to hand around).
Here's a sample object:
class ChartConfig(object):
def __init__(self):
#Drawing properties (Booleans/strings)
self.antialiased = None
self.plot_style = None
self.plot_title = None
self.autoscale = None
#X axis properties (strings/ints)
self.xaxis_title = None
self.xaxis_tick_rotation = None
self.xaxis_tick_align = None
#Y axis properties (strings/ints)
self.yaxis_title = None
self.yaxis_tick_rotation = None
self.yaxis_tick_align = None
#A list of non-primitive objects
self.trace_configs = []
def __copy__(self):
pass
def __deepcopy__(self, memo):
pass
What is the right way to implement the copy
and deepcopy
methods on this object to ensure copy.copy
and copy.deepcopy
give me the proper behavior?
Putting together Alex Martelli's answer and Rob Young's comment you get the following code:
from copy import copy, deepcopy
class A(object):
def __init__(self):
print 'init'
self.v = 10
self.z = [2,3,4]
def __copy__(self):
cls = self.__class__
result = cls.__new__(cls)
result.__dict__.update(self.__dict__)
return result
def __deepcopy__(self, memo):
cls = self.__class__
result = cls.__new__(cls)
memo[id(self)] = result
for k, v in self.__dict__.items():
setattr(result, k, deepcopy(v, memo))
return result
a = A()
a.v = 11
b1, b2 = copy(a), deepcopy(a)
a.v = 12
a.z.append(5)
print b1.v, b1.z
print b2.v, b2.z
prints
init
11 [2, 3, 4, 5]
11 [2, 3, 4]
here __deepcopy__
fills in the memo
dict to avoid excess copying in case the object itself is referenced from its member.