blob: 31adfd331723afc8a18a0096d6fb53e21092f9f4 [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 Rossumc7557582003-02-06 19:53:22 +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
51import types
Guido van Rossum9c9cf412003-02-19 01:20:40 +000052from copy_reg import dispatch_table
Guido van Rossum409780f1995-01-10 00:34:21 +000053
Fred Drake227b1202000-08-17 05:06:49 +000054class Error(Exception):
Tim Peters88869f92001-01-14 23:36:06 +000055 pass
56error = Error # backward compatibility
Guido van Rossum409780f1995-01-10 00:34:21 +000057
Guido van Rossumf8baad02000-11-27 21:53:14 +000058try:
59 from org.python.core import PyStringMap
60except ImportError:
61 PyStringMap = None
62
Guido van Rossumc7557582003-02-06 19:53:22 +000063__all__ = ["Error", "copy", "deepcopy"]
Skip Montanaroe99d5ea2001-01-20 19:54:20 +000064
Guido van Rossum409780f1995-01-10 00:34:21 +000065def copy(x):
Tim Peters88869f92001-01-14 23:36:06 +000066 """Shallow copy operation on arbitrary Python objects.
Guido van Rossumcc6764c1995-02-09 17:18:10 +000067
Tim Peters88869f92001-01-14 23:36:06 +000068 See the module's __doc__ string for more info.
69 """
Guido van Rossumcc6764c1995-02-09 17:18:10 +000070
Guido van Rossumc06e3ac2003-02-07 17:30:18 +000071 cls = type(x)
72
73 copier = _copy_dispatch.get(cls)
74 if copier:
75 return copier(x)
76
77 copier = getattr(cls, "__copy__", None)
78 if copier:
79 return copier(x)
80
81 reductor = dispatch_table.get(cls)
Guido van Rossume6908832003-02-19 01:19:28 +000082 if reductor:
83 rv = reductor(x)
84 else:
85 reductor = getattr(x, "__reduce_ex__", None)
86 if reductor:
87 rv = reductor(2)
88 else:
89 reductor = getattr(x, "__reduce__", None)
90 if reductor:
91 rv = reductor()
92 else:
93 raise Error("un(shallow)copyable object of type %s" % cls)
Guido van Rossumc06e3ac2003-02-07 17:30:18 +000094
Guido van Rossume6908832003-02-19 01:19:28 +000095 return _reconstruct(x, rv, 0)
Tim Petersf2715e02003-02-19 02:35:07 +000096
Guido van Rossumc7557582003-02-06 19:53:22 +000097
Guido van Rossum409780f1995-01-10 00:34:21 +000098_copy_dispatch = d = {}
99
100def _copy_atomic(x):
Tim Peters88869f92001-01-14 23:36:06 +0000101 return x
Guido van Rossum409780f1995-01-10 00:34:21 +0000102d[types.NoneType] = _copy_atomic
103d[types.IntType] = _copy_atomic
104d[types.LongType] = _copy_atomic
105d[types.FloatType] = _copy_atomic
Martin v. Löwis71b75562003-01-16 10:40:00 +0000106d[types.BooleanType] = _copy_atomic
Guido van Rossum8b9def32001-09-28 18:16:13 +0000107try:
108 d[types.ComplexType] = _copy_atomic
109except AttributeError:
110 pass
Guido van Rossum409780f1995-01-10 00:34:21 +0000111d[types.StringType] = _copy_atomic
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000112try:
113 d[types.UnicodeType] = _copy_atomic
114except AttributeError:
115 pass
Guido van Rossum2fff84d1999-01-25 21:37:02 +0000116try:
Tim Peters88869f92001-01-14 23:36:06 +0000117 d[types.CodeType] = _copy_atomic
Guido van Rossum2fff84d1999-01-25 21:37:02 +0000118except AttributeError:
Tim Peters88869f92001-01-14 23:36:06 +0000119 pass
Guido van Rossum409780f1995-01-10 00:34:21 +0000120d[types.TypeType] = _copy_atomic
121d[types.XRangeType] = _copy_atomic
Guido van Rossum55d2f391995-03-14 17:41:36 +0000122d[types.ClassType] = _copy_atomic
Martin v. Löwisba8f5ff2003-06-14 07:10:06 +0000123d[types.BuiltinFunctionType] = _copy_atomic
Guido van Rossum409780f1995-01-10 00:34:21 +0000124
125def _copy_list(x):
Tim Peters88869f92001-01-14 23:36:06 +0000126 return x[:]
Guido van Rossum409780f1995-01-10 00:34:21 +0000127d[types.ListType] = _copy_list
128
129def _copy_tuple(x):
Tim Peters88869f92001-01-14 23:36:06 +0000130 return x[:]
Guido van Rossum409780f1995-01-10 00:34:21 +0000131d[types.TupleType] = _copy_tuple
132
133def _copy_dict(x):
Tim Peters88869f92001-01-14 23:36:06 +0000134 return x.copy()
Guido van Rossum409780f1995-01-10 00:34:21 +0000135d[types.DictionaryType] = _copy_dict
Guido van Rossumf8baad02000-11-27 21:53:14 +0000136if PyStringMap is not None:
137 d[PyStringMap] = _copy_dict
Guido van Rossum409780f1995-01-10 00:34:21 +0000138
139def _copy_inst(x):
Tim Peters88869f92001-01-14 23:36:06 +0000140 if hasattr(x, '__copy__'):
141 return x.__copy__()
142 if hasattr(x, '__getinitargs__'):
143 args = x.__getinitargs__()
Guido van Rossum68468eb2003-02-27 20:14:51 +0000144 y = x.__class__(*args)
Tim Peters88869f92001-01-14 23:36:06 +0000145 else:
146 y = _EmptyClass()
147 y.__class__ = x.__class__
148 if hasattr(x, '__getstate__'):
149 state = x.__getstate__()
150 else:
151 state = x.__dict__
152 if hasattr(y, '__setstate__'):
153 y.__setstate__(state)
154 else:
155 y.__dict__.update(state)
156 return y
Guido van Rossum409780f1995-01-10 00:34:21 +0000157d[types.InstanceType] = _copy_inst
158
159del d
160
Guido van Rossumc06e3ac2003-02-07 17:30:18 +0000161def deepcopy(x, memo=None, _nil=[]):
Tim Peters88869f92001-01-14 23:36:06 +0000162 """Deep copy operation on arbitrary Python objects.
Guido van Rossumcc6764c1995-02-09 17:18:10 +0000163
Tim Peters88869f92001-01-14 23:36:06 +0000164 See the module's __doc__ string for more info.
165 """
Guido van Rossumcc6764c1995-02-09 17:18:10 +0000166
Tim Peters88869f92001-01-14 23:36:06 +0000167 if memo is None:
168 memo = {}
Guido van Rossumc06e3ac2003-02-07 17:30:18 +0000169
Tim Peters88869f92001-01-14 23:36:06 +0000170 d = id(x)
Guido van Rossumc06e3ac2003-02-07 17:30:18 +0000171 y = memo.get(d, _nil)
172 if y is not _nil:
173 return y
174
175 cls = type(x)
176
177 copier = _deepcopy_dispatch.get(cls)
178 if copier:
179 y = copier(x, memo)
180 else:
Tim Peters88869f92001-01-14 23:36:06 +0000181 try:
Guido van Rossumc06e3ac2003-02-07 17:30:18 +0000182 issc = issubclass(cls, type)
183 except TypeError: # cls is not a class (old Boost; see SF #502085)
Guido van Rossum11ade1d2002-06-10 21:10:27 +0000184 issc = 0
185 if issc:
Guido van Rossume6908832003-02-19 01:19:28 +0000186 y = _deepcopy_atomic(x, memo)
Guido van Rossum6cef6d52001-09-28 18:13:29 +0000187 else:
Guido van Rossume6908832003-02-19 01:19:28 +0000188 copier = getattr(x, "__deepcopy__", None)
189 if copier:
190 y = copier(memo)
191 else:
192 reductor = dispatch_table.get(cls)
193 if reductor:
194 rv = reductor(x)
195 else:
196 reductor = getattr(x, "__reduce_ex__", None)
197 if reductor:
198 rv = reductor(2)
199 else:
200 reductor = getattr(x, "__reduce__", None)
201 if reductor:
202 rv = reductor()
203 else:
204 raise Error(
205 "un(deep)copyable object of type %s" % cls)
206 y = _reconstruct(x, rv, 1, memo)
Guido van Rossumc06e3ac2003-02-07 17:30:18 +0000207
Tim Peters88869f92001-01-14 23:36:06 +0000208 memo[d] = y
Guido van Rossum61154602002-08-12 20:20:08 +0000209 _keep_alive(x, memo) # Make sure x lives at least as long as d
Tim Peters88869f92001-01-14 23:36:06 +0000210 return y
Guido van Rossum409780f1995-01-10 00:34:21 +0000211
212_deepcopy_dispatch = d = {}
213
214def _deepcopy_atomic(x, memo):
Tim Peters88869f92001-01-14 23:36:06 +0000215 return x
Guido van Rossum409780f1995-01-10 00:34:21 +0000216d[types.NoneType] = _deepcopy_atomic
217d[types.IntType] = _deepcopy_atomic
218d[types.LongType] = _deepcopy_atomic
219d[types.FloatType] = _deepcopy_atomic
Martin v. Löwis71b75562003-01-16 10:40:00 +0000220d[types.BooleanType] = _deepcopy_atomic
Guido van Rossum8b9def32001-09-28 18:16:13 +0000221try:
222 d[types.ComplexType] = _deepcopy_atomic
223except AttributeError:
224 pass
Guido van Rossum409780f1995-01-10 00:34:21 +0000225d[types.StringType] = _deepcopy_atomic
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000226try:
227 d[types.UnicodeType] = _deepcopy_atomic
228except AttributeError:
229 pass
Guido van Rossum88b666c2002-02-28 23:19:52 +0000230try:
231 d[types.CodeType] = _deepcopy_atomic
232except AttributeError:
233 pass
Guido van Rossum409780f1995-01-10 00:34:21 +0000234d[types.TypeType] = _deepcopy_atomic
235d[types.XRangeType] = _deepcopy_atomic
Guido van Rossum1dca4822003-02-07 17:53:23 +0000236d[types.ClassType] = _deepcopy_atomic
Martin v. Löwisba8f5ff2003-06-14 07:10:06 +0000237d[types.BuiltinFunctionType] = _deepcopy_atomic
Guido van Rossum409780f1995-01-10 00:34:21 +0000238
239def _deepcopy_list(x, memo):
Tim Peters88869f92001-01-14 23:36:06 +0000240 y = []
241 memo[id(x)] = y
242 for a in x:
243 y.append(deepcopy(a, memo))
244 return y
Guido van Rossum409780f1995-01-10 00:34:21 +0000245d[types.ListType] = _deepcopy_list
246
247def _deepcopy_tuple(x, memo):
Tim Peters88869f92001-01-14 23:36:06 +0000248 y = []
249 for a in x:
250 y.append(deepcopy(a, memo))
251 d = id(x)
252 try:
253 return memo[d]
254 except KeyError:
255 pass
256 for i in range(len(x)):
257 if x[i] is not y[i]:
258 y = tuple(y)
259 break
260 else:
261 y = x
262 memo[d] = y
263 return y
Guido van Rossum409780f1995-01-10 00:34:21 +0000264d[types.TupleType] = _deepcopy_tuple
265
266def _deepcopy_dict(x, memo):
Tim Peters88869f92001-01-14 23:36:06 +0000267 y = {}
268 memo[id(x)] = y
Raymond Hettingere0d49722002-06-02 18:55:56 +0000269 for key, value in x.iteritems():
270 y[deepcopy(key, memo)] = deepcopy(value, memo)
Tim Peters88869f92001-01-14 23:36:06 +0000271 return y
Guido van Rossum409780f1995-01-10 00:34:21 +0000272d[types.DictionaryType] = _deepcopy_dict
Guido van Rossumf8baad02000-11-27 21:53:14 +0000273if PyStringMap is not None:
274 d[PyStringMap] = _deepcopy_dict
Guido van Rossum409780f1995-01-10 00:34:21 +0000275
Guido van Rossum558be281997-08-20 22:26:19 +0000276def _keep_alive(x, memo):
Tim Peters88869f92001-01-14 23:36:06 +0000277 """Keeps a reference to the object x in the memo.
Guido van Rossum558be281997-08-20 22:26:19 +0000278
Tim Peters88869f92001-01-14 23:36:06 +0000279 Because we remember objects by their id, we have
280 to assure that possibly temporary objects are kept
281 alive by referencing them.
282 We store a reference at the id of the memo, which should
283 normally not be used unless someone tries to deepcopy
284 the memo itself...
285 """
286 try:
287 memo[id(memo)].append(x)
288 except KeyError:
289 # aha, this is the first one :-)
290 memo[id(memo)]=[x]
Guido van Rossum558be281997-08-20 22:26:19 +0000291
Guido van Rossum409780f1995-01-10 00:34:21 +0000292def _deepcopy_inst(x, memo):
Tim Peters88869f92001-01-14 23:36:06 +0000293 if hasattr(x, '__deepcopy__'):
294 return x.__deepcopy__(memo)
295 if hasattr(x, '__getinitargs__'):
296 args = x.__getinitargs__()
Tim Peters88869f92001-01-14 23:36:06 +0000297 args = deepcopy(args, memo)
Guido van Rossum68468eb2003-02-27 20:14:51 +0000298 y = x.__class__(*args)
Tim Peters88869f92001-01-14 23:36:06 +0000299 else:
300 y = _EmptyClass()
301 y.__class__ = x.__class__
302 memo[id(x)] = y
303 if hasattr(x, '__getstate__'):
304 state = x.__getstate__()
Tim Peters88869f92001-01-14 23:36:06 +0000305 else:
306 state = x.__dict__
307 state = deepcopy(state, memo)
308 if hasattr(y, '__setstate__'):
309 y.__setstate__(state)
310 else:
311 y.__dict__.update(state)
312 return y
Guido van Rossum409780f1995-01-10 00:34:21 +0000313d[types.InstanceType] = _deepcopy_inst
314
Guido van Rossum1e91c142001-12-28 21:33:22 +0000315def _reconstruct(x, info, deep, memo=None):
Guido van Rossum6cef6d52001-09-28 18:13:29 +0000316 if isinstance(info, str):
317 return x
318 assert isinstance(info, tuple)
Guido van Rossum1e91c142001-12-28 21:33:22 +0000319 if memo is None:
320 memo = {}
Guido van Rossum6cef6d52001-09-28 18:13:29 +0000321 n = len(info)
Guido van Rossum90e05b02003-02-06 18:18:23 +0000322 assert n in (2, 3, 4, 5)
Guido van Rossum6cef6d52001-09-28 18:13:29 +0000323 callable, args = info[:2]
324 if n > 2:
325 state = info[2]
326 else:
327 state = {}
Guido van Rossum90e05b02003-02-06 18:18:23 +0000328 if n > 3:
329 listiter = info[3]
330 else:
331 listiter = None
332 if n > 4:
333 dictiter = info[4]
334 else:
335 dictiter = None
Guido van Rossum6cef6d52001-09-28 18:13:29 +0000336 if deep:
Guido van Rossum1e91c142001-12-28 21:33:22 +0000337 args = deepcopy(args, memo)
Guido van Rossum6cef6d52001-09-28 18:13:29 +0000338 y = callable(*args)
Guido van Rossum99d2c252003-06-13 19:28:47 +0000339 memo[id(x)] = y
Guido van Rossum90e05b02003-02-06 18:18:23 +0000340 if listiter is not None:
341 for item in listiter:
342 if deep:
343 item = deepcopy(item, memo)
344 y.append(item)
345 if dictiter is not None:
346 for key, value in dictiter:
347 if deep:
348 key = deepcopy(key, memo)
349 value = deepcopy(value, memo)
350 y[key] = value
Guido van Rossum6cef6d52001-09-28 18:13:29 +0000351 if state:
352 if deep:
Guido van Rossum1e91c142001-12-28 21:33:22 +0000353 state = deepcopy(state, memo)
Guido van Rossum3e3583c2002-06-06 17:41:20 +0000354 if hasattr(y, '__setstate__'):
355 y.__setstate__(state)
356 else:
Guido van Rossumc7557582003-02-06 19:53:22 +0000357 if isinstance(state, tuple) and len(state) == 2:
358 state, slotstate = state
359 else:
360 slotstate = None
361 if state is not None:
362 y.__dict__.update(state)
363 if slotstate is not None:
364 for key, value in slotstate.iteritems():
365 setattr(y, key, value)
Guido van Rossum6cef6d52001-09-28 18:13:29 +0000366 return y
367
Guido van Rossum409780f1995-01-10 00:34:21 +0000368del d
369
370del types
371
Guido van Rossumc5d2d511997-12-07 16:18:22 +0000372# Helper for instance creation without calling __init__
373class _EmptyClass:
374 pass
375
Guido van Rossum409780f1995-01-10 00:34:21 +0000376def _test():
Tim Peters88869f92001-01-14 23:36:06 +0000377 l = [None, 1, 2L, 3.14, 'xyzzy', (1, 2L), [3.14, 'abc'],
378 {'abc': 'ABC'}, (), [], {}]
379 l1 = copy(l)
380 print l1==l
381 l1 = map(copy, l)
382 print l1==l
383 l1 = deepcopy(l)
384 print l1==l
385 class C:
386 def __init__(self, arg=None):
387 self.a = 1
388 self.arg = arg
389 if __name__ == '__main__':
390 import sys
391 file = sys.argv[0]
392 else:
393 file = __file__
394 self.fp = open(file)
395 self.fp.close()
396 def __getstate__(self):
397 return {'a': self.a, 'arg': self.arg}
398 def __setstate__(self, state):
Raymond Hettingere0d49722002-06-02 18:55:56 +0000399 for key, value in state.iteritems():
400 setattr(self, key, value)
Guido van Rossumc06e3ac2003-02-07 17:30:18 +0000401 def __deepcopy__(self, memo=None):
Tim Peters88869f92001-01-14 23:36:06 +0000402 new = self.__class__(deepcopy(self.arg, memo))
403 new.a = self.a
404 return new
405 c = C('argument sketch')
406 l.append(c)
407 l2 = copy(l)
408 print l == l2
409 print l
410 print l2
411 l2 = deepcopy(l)
412 print l == l2
413 print l
414 print l2
415 l.append({l[1]: l, 'xyz': l[2]})
416 l3 = copy(l)
417 import repr
418 print map(repr.repr, l)
419 print map(repr.repr, l1)
420 print map(repr.repr, l2)
421 print map(repr.repr, l3)
422 l3 = deepcopy(l)
423 import repr
424 print map(repr.repr, l)
425 print map(repr.repr, l1)
426 print map(repr.repr, l2)
427 print map(repr.repr, l3)
Guido van Rossum409780f1995-01-10 00:34:21 +0000428
429if __name__ == '__main__':
Tim Peters88869f92001-01-14 23:36:06 +0000430 _test()