blob: d3db93d08d125ec103829ea505ddbf1ce4f88486 [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
Raymond Hettingerf9d88ab2005-06-13 01:10:15 +000017 extent possible) inserts *the same objects* into it that the
Guido van Rossumcc6764c1995-02-09 17:18:10 +000018 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
Antoine Pitrou775fd662009-05-15 16:54:52 +000052import weakref
Georg Brandldffbf5f2008-05-20 07:49:57 +000053from copy_reg import dispatch_table
Guido van Rossum409780f1995-01-10 00:34:21 +000054
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 Rossumc7557582003-02-06 19:53:22 +000064__all__ = ["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
Guido van Rossumc06e3ac2003-02-07 17:30:18 +000072 cls = type(x)
73
74 copier = _copy_dispatch.get(cls)
75 if copier:
76 return copier(x)
77
78 copier = getattr(cls, "__copy__", None)
79 if copier:
80 return copier(x)
81
82 reductor = dispatch_table.get(cls)
Guido van Rossume6908832003-02-19 01:19:28 +000083 if reductor:
84 rv = reductor(x)
85 else:
86 reductor = getattr(x, "__reduce_ex__", None)
87 if reductor:
88 rv = reductor(2)
89 else:
90 reductor = getattr(x, "__reduce__", None)
91 if reductor:
92 rv = reductor()
93 else:
94 raise Error("un(shallow)copyable object of type %s" % cls)
Guido van Rossumc06e3ac2003-02-07 17:30:18 +000095
Guido van Rossume6908832003-02-19 01:19:28 +000096 return _reconstruct(x, rv, 0)
Tim Petersf2715e02003-02-19 02:35:07 +000097
Guido van Rossumc7557582003-02-06 19:53:22 +000098
Guido van Rossum409780f1995-01-10 00:34:21 +000099_copy_dispatch = d = {}
100
Raymond Hettingerf0e35692004-03-08 05:59:33 +0000101def _copy_immutable(x):
Tim Peters88869f92001-01-14 23:36:06 +0000102 return x
Raymond Hettingerf7153662005-02-07 14:16:21 +0000103for t in (type(None), int, long, float, bool, str, tuple,
Raymond Hettingerf0e35692004-03-08 05:59:33 +0000104 frozenset, type, xrange, types.ClassType,
Raymond Hettingerb72233c2008-03-24 08:17:39 +0000105 types.BuiltinFunctionType, type(Ellipsis),
Antoine Pitrou775fd662009-05-15 16:54:52 +0000106 types.FunctionType, weakref.ref):
Raymond Hettingerf0e35692004-03-08 05:59:33 +0000107 d[t] = _copy_immutable
108for name in ("ComplexType", "UnicodeType", "CodeType"):
109 t = getattr(types, name, None)
110 if t is not None:
111 d[t] = _copy_immutable
Guido van Rossum409780f1995-01-10 00:34:21 +0000112
Raymond Hettingerf0e35692004-03-08 05:59:33 +0000113def _copy_with_constructor(x):
114 return type(x)(x)
115for t in (list, dict, set):
116 d[t] = _copy_with_constructor
Guido van Rossum409780f1995-01-10 00:34:21 +0000117
Raymond Hettingerf0e35692004-03-08 05:59:33 +0000118def _copy_with_copy_method(x):
Tim Peters88869f92001-01-14 23:36:06 +0000119 return x.copy()
Guido van Rossumf8baad02000-11-27 21:53:14 +0000120if PyStringMap is not None:
Raymond Hettingerf0e35692004-03-08 05:59:33 +0000121 d[PyStringMap] = _copy_with_copy_method
Guido van Rossum409780f1995-01-10 00:34:21 +0000122
123def _copy_inst(x):
Tim Peters88869f92001-01-14 23:36:06 +0000124 if hasattr(x, '__copy__'):
125 return x.__copy__()
126 if hasattr(x, '__getinitargs__'):
127 args = x.__getinitargs__()
Guido van Rossum68468eb2003-02-27 20:14:51 +0000128 y = x.__class__(*args)
Tim Peters88869f92001-01-14 23:36:06 +0000129 else:
130 y = _EmptyClass()
131 y.__class__ = x.__class__
132 if hasattr(x, '__getstate__'):
133 state = x.__getstate__()
134 else:
135 state = x.__dict__
136 if hasattr(y, '__setstate__'):
137 y.__setstate__(state)
138 else:
139 y.__dict__.update(state)
140 return y
Guido van Rossum409780f1995-01-10 00:34:21 +0000141d[types.InstanceType] = _copy_inst
142
143del d
144
Guido van Rossumc06e3ac2003-02-07 17:30:18 +0000145def deepcopy(x, memo=None, _nil=[]):
Tim Peters88869f92001-01-14 23:36:06 +0000146 """Deep copy operation on arbitrary Python objects.
Guido van Rossumcc6764c1995-02-09 17:18:10 +0000147
Tim Peters88869f92001-01-14 23:36:06 +0000148 See the module's __doc__ string for more info.
149 """
Guido van Rossumcc6764c1995-02-09 17:18:10 +0000150
Tim Peters88869f92001-01-14 23:36:06 +0000151 if memo is None:
152 memo = {}
Guido van Rossumc06e3ac2003-02-07 17:30:18 +0000153
Tim Peters88869f92001-01-14 23:36:06 +0000154 d = id(x)
Guido van Rossumc06e3ac2003-02-07 17:30:18 +0000155 y = memo.get(d, _nil)
156 if y is not _nil:
157 return y
158
159 cls = type(x)
160
161 copier = _deepcopy_dispatch.get(cls)
162 if copier:
163 y = copier(x, memo)
164 else:
Tim Peters88869f92001-01-14 23:36:06 +0000165 try:
Guido van Rossumc06e3ac2003-02-07 17:30:18 +0000166 issc = issubclass(cls, type)
167 except TypeError: # cls is not a class (old Boost; see SF #502085)
Guido van Rossum11ade1d2002-06-10 21:10:27 +0000168 issc = 0
169 if issc:
Guido van Rossume6908832003-02-19 01:19:28 +0000170 y = _deepcopy_atomic(x, memo)
Guido van Rossum6cef6d52001-09-28 18:13:29 +0000171 else:
Guido van Rossume6908832003-02-19 01:19:28 +0000172 copier = getattr(x, "__deepcopy__", None)
173 if copier:
174 y = copier(memo)
175 else:
176 reductor = dispatch_table.get(cls)
177 if reductor:
178 rv = reductor(x)
179 else:
180 reductor = getattr(x, "__reduce_ex__", None)
181 if reductor:
182 rv = reductor(2)
183 else:
184 reductor = getattr(x, "__reduce__", None)
185 if reductor:
186 rv = reductor()
187 else:
188 raise Error(
189 "un(deep)copyable object of type %s" % cls)
190 y = _reconstruct(x, rv, 1, memo)
Guido van Rossumc06e3ac2003-02-07 17:30:18 +0000191
Tim Peters88869f92001-01-14 23:36:06 +0000192 memo[d] = y
Guido van Rossum61154602002-08-12 20:20:08 +0000193 _keep_alive(x, memo) # Make sure x lives at least as long as d
Tim Peters88869f92001-01-14 23:36:06 +0000194 return y
Guido van Rossum409780f1995-01-10 00:34:21 +0000195
196_deepcopy_dispatch = d = {}
197
198def _deepcopy_atomic(x, memo):
Tim Peters88869f92001-01-14 23:36:06 +0000199 return x
Raymond Hettingerf7153662005-02-07 14:16:21 +0000200d[type(None)] = _deepcopy_atomic
Raymond Hettingerb72233c2008-03-24 08:17:39 +0000201d[type(Ellipsis)] = _deepcopy_atomic
Raymond Hettingerf7153662005-02-07 14:16:21 +0000202d[int] = _deepcopy_atomic
203d[long] = _deepcopy_atomic
204d[float] = _deepcopy_atomic
205d[bool] = _deepcopy_atomic
Guido van Rossum8b9def32001-09-28 18:16:13 +0000206try:
Raymond Hettingerf7153662005-02-07 14:16:21 +0000207 d[complex] = _deepcopy_atomic
Martin v. Löwise2713be2005-03-08 15:03:08 +0000208except NameError:
Guido van Rossum8b9def32001-09-28 18:16:13 +0000209 pass
Raymond Hettingerf7153662005-02-07 14:16:21 +0000210d[str] = _deepcopy_atomic
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000211try:
Raymond Hettingerf7153662005-02-07 14:16:21 +0000212 d[unicode] = _deepcopy_atomic
Martin v. Löwise2713be2005-03-08 15:03:08 +0000213except NameError:
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000214 pass
Guido van Rossum88b666c2002-02-28 23:19:52 +0000215try:
216 d[types.CodeType] = _deepcopy_atomic
217except AttributeError:
218 pass
Raymond Hettingerf7153662005-02-07 14:16:21 +0000219d[type] = _deepcopy_atomic
220d[xrange] = _deepcopy_atomic
Guido van Rossum1dca4822003-02-07 17:53:23 +0000221d[types.ClassType] = _deepcopy_atomic
Martin v. Löwisba8f5ff2003-06-14 07:10:06 +0000222d[types.BuiltinFunctionType] = _deepcopy_atomic
Guido van Rossum1968ad32006-02-25 22:38:04 +0000223d[types.FunctionType] = _deepcopy_atomic
Antoine Pitrou775fd662009-05-15 16:54:52 +0000224d[weakref.ref] = _deepcopy_atomic
Guido van Rossum409780f1995-01-10 00:34:21 +0000225
226def _deepcopy_list(x, memo):
Tim Peters88869f92001-01-14 23:36:06 +0000227 y = []
228 memo[id(x)] = y
229 for a in x:
230 y.append(deepcopy(a, memo))
231 return y
Raymond Hettingerf7153662005-02-07 14:16:21 +0000232d[list] = _deepcopy_list
Guido van Rossum409780f1995-01-10 00:34:21 +0000233
234def _deepcopy_tuple(x, memo):
Tim Peters88869f92001-01-14 23:36:06 +0000235 y = []
236 for a in x:
237 y.append(deepcopy(a, memo))
238 d = id(x)
239 try:
240 return memo[d]
241 except KeyError:
242 pass
243 for i in range(len(x)):
244 if x[i] is not y[i]:
245 y = tuple(y)
246 break
247 else:
248 y = x
249 memo[d] = y
250 return y
Raymond Hettingerf7153662005-02-07 14:16:21 +0000251d[tuple] = _deepcopy_tuple
Guido van Rossum409780f1995-01-10 00:34:21 +0000252
253def _deepcopy_dict(x, memo):
Tim Peters88869f92001-01-14 23:36:06 +0000254 y = {}
255 memo[id(x)] = y
Raymond Hettingere0d49722002-06-02 18:55:56 +0000256 for key, value in x.iteritems():
257 y[deepcopy(key, memo)] = deepcopy(value, memo)
Tim Peters88869f92001-01-14 23:36:06 +0000258 return y
Raymond Hettingerf7153662005-02-07 14:16:21 +0000259d[dict] = _deepcopy_dict
Guido van Rossumf8baad02000-11-27 21:53:14 +0000260if PyStringMap is not None:
261 d[PyStringMap] = _deepcopy_dict
Guido van Rossum409780f1995-01-10 00:34:21 +0000262
Guido van Rossum558be281997-08-20 22:26:19 +0000263def _keep_alive(x, memo):
Tim Peters88869f92001-01-14 23:36:06 +0000264 """Keeps a reference to the object x in the memo.
Guido van Rossum558be281997-08-20 22:26:19 +0000265
Tim Peters88869f92001-01-14 23:36:06 +0000266 Because we remember objects by their id, we have
267 to assure that possibly temporary objects are kept
268 alive by referencing them.
269 We store a reference at the id of the memo, which should
270 normally not be used unless someone tries to deepcopy
271 the memo itself...
272 """
273 try:
274 memo[id(memo)].append(x)
275 except KeyError:
276 # aha, this is the first one :-)
277 memo[id(memo)]=[x]
Guido van Rossum558be281997-08-20 22:26:19 +0000278
Guido van Rossum409780f1995-01-10 00:34:21 +0000279def _deepcopy_inst(x, memo):
Tim Peters88869f92001-01-14 23:36:06 +0000280 if hasattr(x, '__deepcopy__'):
281 return x.__deepcopy__(memo)
282 if hasattr(x, '__getinitargs__'):
283 args = x.__getinitargs__()
Tim Peters88869f92001-01-14 23:36:06 +0000284 args = deepcopy(args, memo)
Guido van Rossum68468eb2003-02-27 20:14:51 +0000285 y = x.__class__(*args)
Tim Peters88869f92001-01-14 23:36:06 +0000286 else:
287 y = _EmptyClass()
288 y.__class__ = x.__class__
289 memo[id(x)] = y
290 if hasattr(x, '__getstate__'):
291 state = x.__getstate__()
Tim Peters88869f92001-01-14 23:36:06 +0000292 else:
293 state = x.__dict__
294 state = deepcopy(state, memo)
295 if hasattr(y, '__setstate__'):
296 y.__setstate__(state)
297 else:
298 y.__dict__.update(state)
299 return y
Guido van Rossum409780f1995-01-10 00:34:21 +0000300d[types.InstanceType] = _deepcopy_inst
301
Guido van Rossum1e91c142001-12-28 21:33:22 +0000302def _reconstruct(x, info, deep, memo=None):
Guido van Rossum6cef6d52001-09-28 18:13:29 +0000303 if isinstance(info, str):
304 return x
305 assert isinstance(info, tuple)
Guido van Rossum1e91c142001-12-28 21:33:22 +0000306 if memo is None:
307 memo = {}
Guido van Rossum6cef6d52001-09-28 18:13:29 +0000308 n = len(info)
Guido van Rossum90e05b02003-02-06 18:18:23 +0000309 assert n in (2, 3, 4, 5)
Guido van Rossum6cef6d52001-09-28 18:13:29 +0000310 callable, args = info[:2]
311 if n > 2:
312 state = info[2]
313 else:
314 state = {}
Guido van Rossum90e05b02003-02-06 18:18:23 +0000315 if n > 3:
316 listiter = info[3]
317 else:
318 listiter = None
319 if n > 4:
320 dictiter = info[4]
321 else:
322 dictiter = None
Guido van Rossum6cef6d52001-09-28 18:13:29 +0000323 if deep:
Guido van Rossum1e91c142001-12-28 21:33:22 +0000324 args = deepcopy(args, memo)
Guido van Rossum6cef6d52001-09-28 18:13:29 +0000325 y = callable(*args)
Guido van Rossum99d2c252003-06-13 19:28:47 +0000326 memo[id(x)] = y
Guido van Rossum90e05b02003-02-06 18:18:23 +0000327 if listiter is not None:
328 for item in listiter:
329 if deep:
330 item = deepcopy(item, memo)
331 y.append(item)
332 if dictiter is not None:
333 for key, value in dictiter:
334 if deep:
335 key = deepcopy(key, memo)
336 value = deepcopy(value, memo)
337 y[key] = value
Guido van Rossum6cef6d52001-09-28 18:13:29 +0000338 if state:
339 if deep:
Guido van Rossum1e91c142001-12-28 21:33:22 +0000340 state = deepcopy(state, memo)
Guido van Rossum3e3583c2002-06-06 17:41:20 +0000341 if hasattr(y, '__setstate__'):
342 y.__setstate__(state)
343 else:
Guido van Rossumc7557582003-02-06 19:53:22 +0000344 if isinstance(state, tuple) and len(state) == 2:
345 state, slotstate = state
346 else:
347 slotstate = None
348 if state is not None:
349 y.__dict__.update(state)
350 if slotstate is not None:
351 for key, value in slotstate.iteritems():
352 setattr(y, key, value)
Guido van Rossum6cef6d52001-09-28 18:13:29 +0000353 return y
354
Guido van Rossum409780f1995-01-10 00:34:21 +0000355del d
356
357del types
358
Guido van Rossumc5d2d511997-12-07 16:18:22 +0000359# Helper for instance creation without calling __init__
360class _EmptyClass:
361 pass
362
Guido van Rossum409780f1995-01-10 00:34:21 +0000363def _test():
Tim Peters88869f92001-01-14 23:36:06 +0000364 l = [None, 1, 2L, 3.14, 'xyzzy', (1, 2L), [3.14, 'abc'],
365 {'abc': 'ABC'}, (), [], {}]
366 l1 = copy(l)
367 print l1==l
368 l1 = map(copy, l)
369 print l1==l
370 l1 = deepcopy(l)
371 print l1==l
372 class C:
373 def __init__(self, arg=None):
374 self.a = 1
375 self.arg = arg
376 if __name__ == '__main__':
377 import sys
378 file = sys.argv[0]
379 else:
380 file = __file__
381 self.fp = open(file)
382 self.fp.close()
383 def __getstate__(self):
384 return {'a': self.a, 'arg': self.arg}
385 def __setstate__(self, state):
Raymond Hettingere0d49722002-06-02 18:55:56 +0000386 for key, value in state.iteritems():
387 setattr(self, key, value)
Guido van Rossumc06e3ac2003-02-07 17:30:18 +0000388 def __deepcopy__(self, memo=None):
Tim Peters88869f92001-01-14 23:36:06 +0000389 new = self.__class__(deepcopy(self.arg, memo))
390 new.a = self.a
391 return new
392 c = C('argument sketch')
393 l.append(c)
394 l2 = copy(l)
395 print l == l2
396 print l
397 print l2
398 l2 = deepcopy(l)
399 print l == l2
400 print l
401 print l2
402 l.append({l[1]: l, 'xyz': l[2]})
403 l3 = copy(l)
Brett Cannon2ee0e8e2008-05-23 05:03:59 +0000404 import repr
405 print map(repr.repr, l)
406 print map(repr.repr, l1)
407 print map(repr.repr, l2)
408 print map(repr.repr, l3)
Tim Peters88869f92001-01-14 23:36:06 +0000409 l3 = deepcopy(l)
Brett Cannon2ee0e8e2008-05-23 05:03:59 +0000410 import repr
411 print map(repr.repr, l)
412 print map(repr.repr, l1)
413 print map(repr.repr, l2)
414 print map(repr.repr, l3)
Guido van Rossum409780f1995-01-10 00:34:21 +0000415
416if __name__ == '__main__':
Tim Peters88869f92001-01-14 23:36:06 +0000417 _test()