blob: 14eff057345c6e56ea335281f57c217596dfcb34 [file] [log] [blame]
Guido van Rossum4b8c6ea2000-02-04 15:39:30 +00001"""Generic (shallow and deep) copying operations.
Guido van Rossum409780f1995-01-10 00:34:21 +00002
Guido van Rossumcc6764c1995-02-09 17:18:10 +00003Interface summary:
4
Tim Peters88869f92001-01-14 23:36:06 +00005 import copy
Guido van Rossumcc6764c1995-02-09 17:18:10 +00006
Tim Peters88869f92001-01-14 23:36:06 +00007 x = copy.copy(y) # make a shallow copy of y
8 x = copy.deepcopy(y) # make a deep copy of y
Guido van Rossumcc6764c1995-02-09 17:18:10 +00009
Guido van Rossum55d2f391995-03-14 17:41:36 +000010For module specific errors, copy.error is raised.
Guido van Rossumcc6764c1995-02-09 17:18:10 +000011
12The difference between shallow and deep copying is only relevant for
13compound objects (objects that contain other objects, like lists or
14class instances).
15
16- A shallow copy constructs a new compound object and then (to the
17 extent possible) inserts *the same objects* into in that the
18 original contains.
19
20- A deep copy constructs a new compound object and then, recursively,
21 inserts *copies* into it of the objects found in the original.
22
23Two problems often exist with deep copy operations that don't exist
24with shallow copy operations:
25
Guido van Rossumf7cea101997-05-28 19:31:14 +000026 a) recursive objects (compound objects that, directly or indirectly,
Guido van Rossumcc6764c1995-02-09 17:18:10 +000027 contain a reference to themselves) may cause a recursive loop
28
Guido van Rossumf7cea101997-05-28 19:31:14 +000029 b) because deep copy copies *everything* it may copy too much, e.g.
Guido van Rossumcc6764c1995-02-09 17:18:10 +000030 administrative data structures that should be shared even between
31 copies
32
33Python's deep copy operation avoids these problems by:
34
Guido van Rossumf7cea101997-05-28 19:31:14 +000035 a) keeping a table of objects already copied during the current
36 copying pass
Guido van Rossumcc6764c1995-02-09 17:18:10 +000037
Guido van Rossumf7cea101997-05-28 19:31:14 +000038 b) letting user-defined classes override the copying operation or the
Guido van Rossumcc6764c1995-02-09 17:18:10 +000039 set of components copied
40
41This version does not copy types like module, class, function, method,
42nor stack trace, stack frame, nor file, socket, window, nor array, nor
43any similar types.
44
45Classes can use the same interfaces to control copying that they use
46to control pickling: they can define methods called __getinitargs__(),
Guido van Rossumc5d2d511997-12-07 16:18:22 +000047__getstate__() and __setstate__(). See the documentation for module
Guido van Rossumcc6764c1995-02-09 17:18:10 +000048"pickle" for information on these methods.
49"""
Guido van Rossum409780f1995-01-10 00:34:21 +000050
Guido van Rossumabfdd701997-10-07 14:47:50 +000051# XXX need to support copy_reg here too...
52
Guido van Rossum409780f1995-01-10 00:34:21 +000053import types
54
Fred Drake227b1202000-08-17 05:06:49 +000055class Error(Exception):
Tim Peters88869f92001-01-14 23:36:06 +000056 pass
57error = Error # backward compatibility
Guido van Rossum409780f1995-01-10 00:34:21 +000058
Guido van Rossumf8baad02000-11-27 21:53:14 +000059try:
60 from org.python.core import PyStringMap
61except ImportError:
62 PyStringMap = None
63
Guido van Rossum6cef6d52001-09-28 18:13:29 +000064__all__ = ["Error", "error", "copy", "deepcopy"]
Skip Montanaroe99d5ea2001-01-20 19:54:20 +000065
Guido van Rossum409780f1995-01-10 00:34:21 +000066def copy(x):
Tim Peters88869f92001-01-14 23:36:06 +000067 """Shallow copy operation on arbitrary Python objects.
Guido van Rossumcc6764c1995-02-09 17:18:10 +000068
Tim Peters88869f92001-01-14 23:36:06 +000069 See the module's __doc__ string for more info.
70 """
Guido van Rossumcc6764c1995-02-09 17:18:10 +000071
Tim Peters88869f92001-01-14 23:36:06 +000072 try:
73 copierfunction = _copy_dispatch[type(x)]
74 except KeyError:
75 try:
76 copier = x.__copy__
77 except AttributeError:
Guido van Rossum6cef6d52001-09-28 18:13:29 +000078 try:
79 reductor = x.__reduce__
80 except AttributeError:
81 raise error, \
82 "un(shallow)copyable object of type %s" % type(x)
83 else:
84 y = _reconstruct(x, reductor(), 0)
85 else:
86 y = copier()
Tim Peters88869f92001-01-14 23:36:06 +000087 else:
88 y = copierfunction(x)
89 return y
Guido van Rossum409780f1995-01-10 00:34:21 +000090
91_copy_dispatch = d = {}
92
93def _copy_atomic(x):
Tim Peters88869f92001-01-14 23:36:06 +000094 return x
Guido van Rossum409780f1995-01-10 00:34:21 +000095d[types.NoneType] = _copy_atomic
96d[types.IntType] = _copy_atomic
97d[types.LongType] = _copy_atomic
98d[types.FloatType] = _copy_atomic
Guido van Rossum8b9def32001-09-28 18:16:13 +000099try:
100 d[types.ComplexType] = _copy_atomic
101except AttributeError:
102 pass
Guido van Rossum409780f1995-01-10 00:34:21 +0000103d[types.StringType] = _copy_atomic
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000104try:
105 d[types.UnicodeType] = _copy_atomic
106except AttributeError:
107 pass
Guido van Rossum2fff84d1999-01-25 21:37:02 +0000108try:
Tim Peters88869f92001-01-14 23:36:06 +0000109 d[types.CodeType] = _copy_atomic
Guido van Rossum2fff84d1999-01-25 21:37:02 +0000110except AttributeError:
Tim Peters88869f92001-01-14 23:36:06 +0000111 pass
Guido van Rossum409780f1995-01-10 00:34:21 +0000112d[types.TypeType] = _copy_atomic
113d[types.XRangeType] = _copy_atomic
Guido van Rossum55d2f391995-03-14 17:41:36 +0000114d[types.ClassType] = _copy_atomic
Guido van Rossum409780f1995-01-10 00:34:21 +0000115
116def _copy_list(x):
Tim Peters88869f92001-01-14 23:36:06 +0000117 return x[:]
Guido van Rossum409780f1995-01-10 00:34:21 +0000118d[types.ListType] = _copy_list
119
120def _copy_tuple(x):
Tim Peters88869f92001-01-14 23:36:06 +0000121 return x[:]
Guido van Rossum409780f1995-01-10 00:34:21 +0000122d[types.TupleType] = _copy_tuple
123
124def _copy_dict(x):
Tim Peters88869f92001-01-14 23:36:06 +0000125 return x.copy()
Guido van Rossum409780f1995-01-10 00:34:21 +0000126d[types.DictionaryType] = _copy_dict
Guido van Rossumf8baad02000-11-27 21:53:14 +0000127if PyStringMap is not None:
128 d[PyStringMap] = _copy_dict
Guido van Rossum409780f1995-01-10 00:34:21 +0000129
130def _copy_inst(x):
Tim Peters88869f92001-01-14 23:36:06 +0000131 if hasattr(x, '__copy__'):
132 return x.__copy__()
133 if hasattr(x, '__getinitargs__'):
134 args = x.__getinitargs__()
135 y = apply(x.__class__, args)
136 else:
137 y = _EmptyClass()
138 y.__class__ = x.__class__
139 if hasattr(x, '__getstate__'):
140 state = x.__getstate__()
141 else:
142 state = x.__dict__
143 if hasattr(y, '__setstate__'):
144 y.__setstate__(state)
145 else:
146 y.__dict__.update(state)
147 return y
Guido van Rossum409780f1995-01-10 00:34:21 +0000148d[types.InstanceType] = _copy_inst
149
150del d
151
152def deepcopy(x, memo = None):
Tim Peters88869f92001-01-14 23:36:06 +0000153 """Deep copy operation on arbitrary Python objects.
Guido van Rossumcc6764c1995-02-09 17:18:10 +0000154
Tim Peters88869f92001-01-14 23:36:06 +0000155 See the module's __doc__ string for more info.
156 """
Guido van Rossumcc6764c1995-02-09 17:18:10 +0000157
Tim Peters88869f92001-01-14 23:36:06 +0000158 if memo is None:
159 memo = {}
160 d = id(x)
161 if memo.has_key(d):
162 return memo[d]
163 try:
164 copierfunction = _deepcopy_dispatch[type(x)]
165 except KeyError:
166 try:
167 copier = x.__deepcopy__
168 except AttributeError:
Guido van Rossum6cef6d52001-09-28 18:13:29 +0000169 try:
170 reductor = x.__reduce__
171 except AttributeError:
172 raise error, \
173 "un-deep-copyable object of type %s" % type(x)
174 else:
175 y = _reconstruct(x, reductor(), 1)
176 else:
177 y = copier(memo)
Tim Peters88869f92001-01-14 23:36:06 +0000178 else:
179 y = copierfunction(x, memo)
180 memo[d] = y
181 return y
Guido van Rossum409780f1995-01-10 00:34:21 +0000182
183_deepcopy_dispatch = d = {}
184
185def _deepcopy_atomic(x, memo):
Tim Peters88869f92001-01-14 23:36:06 +0000186 return x
Guido van Rossum409780f1995-01-10 00:34:21 +0000187d[types.NoneType] = _deepcopy_atomic
188d[types.IntType] = _deepcopy_atomic
189d[types.LongType] = _deepcopy_atomic
190d[types.FloatType] = _deepcopy_atomic
Guido van Rossum8b9def32001-09-28 18:16:13 +0000191try:
192 d[types.ComplexType] = _deepcopy_atomic
193except AttributeError:
194 pass
Guido van Rossum409780f1995-01-10 00:34:21 +0000195d[types.StringType] = _deepcopy_atomic
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000196try:
197 d[types.UnicodeType] = _deepcopy_atomic
198except AttributeError:
199 pass
Guido van Rossum409780f1995-01-10 00:34:21 +0000200d[types.CodeType] = _deepcopy_atomic
201d[types.TypeType] = _deepcopy_atomic
202d[types.XRangeType] = _deepcopy_atomic
203
204def _deepcopy_list(x, memo):
Tim Peters88869f92001-01-14 23:36:06 +0000205 y = []
206 memo[id(x)] = y
207 for a in x:
208 y.append(deepcopy(a, memo))
209 return y
Guido van Rossum409780f1995-01-10 00:34:21 +0000210d[types.ListType] = _deepcopy_list
211
212def _deepcopy_tuple(x, memo):
Tim Peters88869f92001-01-14 23:36:06 +0000213 y = []
214 for a in x:
215 y.append(deepcopy(a, memo))
216 d = id(x)
217 try:
218 return memo[d]
219 except KeyError:
220 pass
221 for i in range(len(x)):
222 if x[i] is not y[i]:
223 y = tuple(y)
224 break
225 else:
226 y = x
227 memo[d] = y
228 return y
Guido van Rossum409780f1995-01-10 00:34:21 +0000229d[types.TupleType] = _deepcopy_tuple
230
231def _deepcopy_dict(x, memo):
Tim Peters88869f92001-01-14 23:36:06 +0000232 y = {}
233 memo[id(x)] = y
234 for key in x.keys():
235 y[deepcopy(key, memo)] = deepcopy(x[key], memo)
236 return y
Guido van Rossum409780f1995-01-10 00:34:21 +0000237d[types.DictionaryType] = _deepcopy_dict
Guido van Rossumf8baad02000-11-27 21:53:14 +0000238if PyStringMap is not None:
239 d[PyStringMap] = _deepcopy_dict
Guido van Rossum409780f1995-01-10 00:34:21 +0000240
Guido van Rossum558be281997-08-20 22:26:19 +0000241def _keep_alive(x, memo):
Tim Peters88869f92001-01-14 23:36:06 +0000242 """Keeps a reference to the object x in the memo.
Guido van Rossum558be281997-08-20 22:26:19 +0000243
Tim Peters88869f92001-01-14 23:36:06 +0000244 Because we remember objects by their id, we have
245 to assure that possibly temporary objects are kept
246 alive by referencing them.
247 We store a reference at the id of the memo, which should
248 normally not be used unless someone tries to deepcopy
249 the memo itself...
250 """
251 try:
252 memo[id(memo)].append(x)
253 except KeyError:
254 # aha, this is the first one :-)
255 memo[id(memo)]=[x]
Guido van Rossum558be281997-08-20 22:26:19 +0000256
Guido van Rossum409780f1995-01-10 00:34:21 +0000257def _deepcopy_inst(x, memo):
Tim Peters88869f92001-01-14 23:36:06 +0000258 if hasattr(x, '__deepcopy__'):
259 return x.__deepcopy__(memo)
260 if hasattr(x, '__getinitargs__'):
261 args = x.__getinitargs__()
262 _keep_alive(args, memo)
263 args = deepcopy(args, memo)
264 y = apply(x.__class__, args)
265 else:
266 y = _EmptyClass()
267 y.__class__ = x.__class__
268 memo[id(x)] = y
269 if hasattr(x, '__getstate__'):
270 state = x.__getstate__()
271 _keep_alive(state, memo)
272 else:
273 state = x.__dict__
274 state = deepcopy(state, memo)
275 if hasattr(y, '__setstate__'):
276 y.__setstate__(state)
277 else:
278 y.__dict__.update(state)
279 return y
Guido van Rossum409780f1995-01-10 00:34:21 +0000280d[types.InstanceType] = _deepcopy_inst
281
Guido van Rossum6cef6d52001-09-28 18:13:29 +0000282def _reconstruct(x, info, deep):
283 if isinstance(info, str):
284 return x
285 assert isinstance(info, tuple)
286 n = len(info)
287 assert n in (2, 3)
288 callable, args = info[:2]
289 if n > 2:
290 state = info[2]
291 else:
292 state = {}
293 if deep:
294 args = deepcopy(args)
295 y = callable(*args)
296 if state:
297 if deep:
298 state = deepcopy(state)
299 y.__dict__.update(state)
300 return y
301
Guido van Rossum409780f1995-01-10 00:34:21 +0000302del d
303
304del types
305
Guido van Rossumc5d2d511997-12-07 16:18:22 +0000306# Helper for instance creation without calling __init__
307class _EmptyClass:
308 pass
309
Guido van Rossum409780f1995-01-10 00:34:21 +0000310def _test():
Tim Peters88869f92001-01-14 23:36:06 +0000311 l = [None, 1, 2L, 3.14, 'xyzzy', (1, 2L), [3.14, 'abc'],
312 {'abc': 'ABC'}, (), [], {}]
313 l1 = copy(l)
314 print l1==l
315 l1 = map(copy, l)
316 print l1==l
317 l1 = deepcopy(l)
318 print l1==l
319 class C:
320 def __init__(self, arg=None):
321 self.a = 1
322 self.arg = arg
323 if __name__ == '__main__':
324 import sys
325 file = sys.argv[0]
326 else:
327 file = __file__
328 self.fp = open(file)
329 self.fp.close()
330 def __getstate__(self):
331 return {'a': self.a, 'arg': self.arg}
332 def __setstate__(self, state):
333 for key in state.keys():
334 setattr(self, key, state[key])
335 def __deepcopy__(self, memo = None):
336 new = self.__class__(deepcopy(self.arg, memo))
337 new.a = self.a
338 return new
339 c = C('argument sketch')
340 l.append(c)
341 l2 = copy(l)
342 print l == l2
343 print l
344 print l2
345 l2 = deepcopy(l)
346 print l == l2
347 print l
348 print l2
349 l.append({l[1]: l, 'xyz': l[2]})
350 l3 = copy(l)
351 import repr
352 print map(repr.repr, l)
353 print map(repr.repr, l1)
354 print map(repr.repr, l2)
355 print map(repr.repr, l3)
356 l3 = deepcopy(l)
357 import repr
358 print map(repr.repr, l)
359 print map(repr.repr, l1)
360 print map(repr.repr, l2)
361 print map(repr.repr, l3)
Guido van Rossum409780f1995-01-10 00:34:21 +0000362
363if __name__ == '__main__':
Tim Peters88869f92001-01-14 23:36:06 +0000364 _test()