blob: b216beb33642afa3673e9c147834ead480158c86 [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
Raymond Hettingerf0e35692004-03-08 05:59:33 +0000100def _copy_immutable(x):
Tim Peters88869f92001-01-14 23:36:06 +0000101 return x
Raymond Hettingerf7153662005-02-07 14:16:21 +0000102for t in (type(None), int, long, float, bool, str, tuple,
Raymond Hettingerf0e35692004-03-08 05:59:33 +0000103 frozenset, type, xrange, types.ClassType,
104 types.BuiltinFunctionType):
105 d[t] = _copy_immutable
106for name in ("ComplexType", "UnicodeType", "CodeType"):
107 t = getattr(types, name, None)
108 if t is not None:
109 d[t] = _copy_immutable
Guido van Rossum409780f1995-01-10 00:34:21 +0000110
Raymond Hettingerf0e35692004-03-08 05:59:33 +0000111def _copy_with_constructor(x):
112 return type(x)(x)
113for t in (list, dict, set):
114 d[t] = _copy_with_constructor
Guido van Rossum409780f1995-01-10 00:34:21 +0000115
Raymond Hettingerf0e35692004-03-08 05:59:33 +0000116def _copy_with_copy_method(x):
Tim Peters88869f92001-01-14 23:36:06 +0000117 return x.copy()
Guido van Rossumf8baad02000-11-27 21:53:14 +0000118if PyStringMap is not None:
Raymond Hettingerf0e35692004-03-08 05:59:33 +0000119 d[PyStringMap] = _copy_with_copy_method
Guido van Rossum409780f1995-01-10 00:34:21 +0000120
121def _copy_inst(x):
Tim Peters88869f92001-01-14 23:36:06 +0000122 if hasattr(x, '__copy__'):
123 return x.__copy__()
124 if hasattr(x, '__getinitargs__'):
125 args = x.__getinitargs__()
Guido van Rossum68468eb2003-02-27 20:14:51 +0000126 y = x.__class__(*args)
Tim Peters88869f92001-01-14 23:36:06 +0000127 else:
128 y = _EmptyClass()
129 y.__class__ = x.__class__
130 if hasattr(x, '__getstate__'):
131 state = x.__getstate__()
132 else:
133 state = x.__dict__
134 if hasattr(y, '__setstate__'):
135 y.__setstate__(state)
136 else:
137 y.__dict__.update(state)
138 return y
Guido van Rossum409780f1995-01-10 00:34:21 +0000139d[types.InstanceType] = _copy_inst
140
141del d
142
Guido van Rossumc06e3ac2003-02-07 17:30:18 +0000143def deepcopy(x, memo=None, _nil=[]):
Tim Peters88869f92001-01-14 23:36:06 +0000144 """Deep copy operation on arbitrary Python objects.
Guido van Rossumcc6764c1995-02-09 17:18:10 +0000145
Tim Peters88869f92001-01-14 23:36:06 +0000146 See the module's __doc__ string for more info.
147 """
Guido van Rossumcc6764c1995-02-09 17:18:10 +0000148
Tim Peters88869f92001-01-14 23:36:06 +0000149 if memo is None:
150 memo = {}
Guido van Rossumc06e3ac2003-02-07 17:30:18 +0000151
Tim Peters88869f92001-01-14 23:36:06 +0000152 d = id(x)
Guido van Rossumc06e3ac2003-02-07 17:30:18 +0000153 y = memo.get(d, _nil)
154 if y is not _nil:
155 return y
156
157 cls = type(x)
158
159 copier = _deepcopy_dispatch.get(cls)
160 if copier:
161 y = copier(x, memo)
162 else:
Tim Peters88869f92001-01-14 23:36:06 +0000163 try:
Guido van Rossumc06e3ac2003-02-07 17:30:18 +0000164 issc = issubclass(cls, type)
165 except TypeError: # cls is not a class (old Boost; see SF #502085)
Guido van Rossum11ade1d2002-06-10 21:10:27 +0000166 issc = 0
167 if issc:
Guido van Rossume6908832003-02-19 01:19:28 +0000168 y = _deepcopy_atomic(x, memo)
Guido van Rossum6cef6d52001-09-28 18:13:29 +0000169 else:
Guido van Rossume6908832003-02-19 01:19:28 +0000170 copier = getattr(x, "__deepcopy__", None)
171 if copier:
172 y = copier(memo)
173 else:
174 reductor = dispatch_table.get(cls)
175 if reductor:
176 rv = reductor(x)
177 else:
178 reductor = getattr(x, "__reduce_ex__", None)
179 if reductor:
180 rv = reductor(2)
181 else:
182 reductor = getattr(x, "__reduce__", None)
183 if reductor:
184 rv = reductor()
185 else:
186 raise Error(
187 "un(deep)copyable object of type %s" % cls)
188 y = _reconstruct(x, rv, 1, memo)
Guido van Rossumc06e3ac2003-02-07 17:30:18 +0000189
Tim Peters88869f92001-01-14 23:36:06 +0000190 memo[d] = y
Guido van Rossum61154602002-08-12 20:20:08 +0000191 _keep_alive(x, memo) # Make sure x lives at least as long as d
Tim Peters88869f92001-01-14 23:36:06 +0000192 return y
Guido van Rossum409780f1995-01-10 00:34:21 +0000193
194_deepcopy_dispatch = d = {}
195
196def _deepcopy_atomic(x, memo):
Tim Peters88869f92001-01-14 23:36:06 +0000197 return x
Raymond Hettingerf7153662005-02-07 14:16:21 +0000198d[type(None)] = _deepcopy_atomic
199d[int] = _deepcopy_atomic
200d[long] = _deepcopy_atomic
201d[float] = _deepcopy_atomic
202d[bool] = _deepcopy_atomic
Guido van Rossum8b9def32001-09-28 18:16:13 +0000203try:
Raymond Hettingerf7153662005-02-07 14:16:21 +0000204 d[complex] = _deepcopy_atomic
Guido van Rossum8b9def32001-09-28 18:16:13 +0000205except AttributeError:
206 pass
Raymond Hettingerf7153662005-02-07 14:16:21 +0000207d[str] = _deepcopy_atomic
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000208try:
Raymond Hettingerf7153662005-02-07 14:16:21 +0000209 d[unicode] = _deepcopy_atomic
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000210except AttributeError:
211 pass
Guido van Rossum88b666c2002-02-28 23:19:52 +0000212try:
213 d[types.CodeType] = _deepcopy_atomic
214except AttributeError:
215 pass
Raymond Hettingerf7153662005-02-07 14:16:21 +0000216d[type] = _deepcopy_atomic
217d[xrange] = _deepcopy_atomic
Guido van Rossum1dca4822003-02-07 17:53:23 +0000218d[types.ClassType] = _deepcopy_atomic
Martin v. Löwisba8f5ff2003-06-14 07:10:06 +0000219d[types.BuiltinFunctionType] = _deepcopy_atomic
Guido van Rossum409780f1995-01-10 00:34:21 +0000220
221def _deepcopy_list(x, memo):
Tim Peters88869f92001-01-14 23:36:06 +0000222 y = []
223 memo[id(x)] = y
224 for a in x:
225 y.append(deepcopy(a, memo))
226 return y
Raymond Hettingerf7153662005-02-07 14:16:21 +0000227d[list] = _deepcopy_list
Guido van Rossum409780f1995-01-10 00:34:21 +0000228
229def _deepcopy_tuple(x, memo):
Tim Peters88869f92001-01-14 23:36:06 +0000230 y = []
231 for a in x:
232 y.append(deepcopy(a, memo))
233 d = id(x)
234 try:
235 return memo[d]
236 except KeyError:
237 pass
238 for i in range(len(x)):
239 if x[i] is not y[i]:
240 y = tuple(y)
241 break
242 else:
243 y = x
244 memo[d] = y
245 return y
Raymond Hettingerf7153662005-02-07 14:16:21 +0000246d[tuple] = _deepcopy_tuple
Guido van Rossum409780f1995-01-10 00:34:21 +0000247
248def _deepcopy_dict(x, memo):
Tim Peters88869f92001-01-14 23:36:06 +0000249 y = {}
250 memo[id(x)] = y
Raymond Hettingere0d49722002-06-02 18:55:56 +0000251 for key, value in x.iteritems():
252 y[deepcopy(key, memo)] = deepcopy(value, memo)
Tim Peters88869f92001-01-14 23:36:06 +0000253 return y
Raymond Hettingerf7153662005-02-07 14:16:21 +0000254d[dict] = _deepcopy_dict
Guido van Rossumf8baad02000-11-27 21:53:14 +0000255if PyStringMap is not None:
256 d[PyStringMap] = _deepcopy_dict
Guido van Rossum409780f1995-01-10 00:34:21 +0000257
Guido van Rossum558be281997-08-20 22:26:19 +0000258def _keep_alive(x, memo):
Tim Peters88869f92001-01-14 23:36:06 +0000259 """Keeps a reference to the object x in the memo.
Guido van Rossum558be281997-08-20 22:26:19 +0000260
Tim Peters88869f92001-01-14 23:36:06 +0000261 Because we remember objects by their id, we have
262 to assure that possibly temporary objects are kept
263 alive by referencing them.
264 We store a reference at the id of the memo, which should
265 normally not be used unless someone tries to deepcopy
266 the memo itself...
267 """
268 try:
269 memo[id(memo)].append(x)
270 except KeyError:
271 # aha, this is the first one :-)
272 memo[id(memo)]=[x]
Guido van Rossum558be281997-08-20 22:26:19 +0000273
Guido van Rossum409780f1995-01-10 00:34:21 +0000274def _deepcopy_inst(x, memo):
Tim Peters88869f92001-01-14 23:36:06 +0000275 if hasattr(x, '__deepcopy__'):
276 return x.__deepcopy__(memo)
277 if hasattr(x, '__getinitargs__'):
278 args = x.__getinitargs__()
Tim Peters88869f92001-01-14 23:36:06 +0000279 args = deepcopy(args, memo)
Guido van Rossum68468eb2003-02-27 20:14:51 +0000280 y = x.__class__(*args)
Tim Peters88869f92001-01-14 23:36:06 +0000281 else:
282 y = _EmptyClass()
283 y.__class__ = x.__class__
284 memo[id(x)] = y
285 if hasattr(x, '__getstate__'):
286 state = x.__getstate__()
Tim Peters88869f92001-01-14 23:36:06 +0000287 else:
288 state = x.__dict__
289 state = deepcopy(state, memo)
290 if hasattr(y, '__setstate__'):
291 y.__setstate__(state)
292 else:
293 y.__dict__.update(state)
294 return y
Guido van Rossum409780f1995-01-10 00:34:21 +0000295d[types.InstanceType] = _deepcopy_inst
296
Guido van Rossum1e91c142001-12-28 21:33:22 +0000297def _reconstruct(x, info, deep, memo=None):
Guido van Rossum6cef6d52001-09-28 18:13:29 +0000298 if isinstance(info, str):
299 return x
300 assert isinstance(info, tuple)
Guido van Rossum1e91c142001-12-28 21:33:22 +0000301 if memo is None:
302 memo = {}
Guido van Rossum6cef6d52001-09-28 18:13:29 +0000303 n = len(info)
Guido van Rossum90e05b02003-02-06 18:18:23 +0000304 assert n in (2, 3, 4, 5)
Guido van Rossum6cef6d52001-09-28 18:13:29 +0000305 callable, args = info[:2]
306 if n > 2:
307 state = info[2]
308 else:
309 state = {}
Guido van Rossum90e05b02003-02-06 18:18:23 +0000310 if n > 3:
311 listiter = info[3]
312 else:
313 listiter = None
314 if n > 4:
315 dictiter = info[4]
316 else:
317 dictiter = None
Guido van Rossum6cef6d52001-09-28 18:13:29 +0000318 if deep:
Guido van Rossum1e91c142001-12-28 21:33:22 +0000319 args = deepcopy(args, memo)
Guido van Rossum6cef6d52001-09-28 18:13:29 +0000320 y = callable(*args)
Guido van Rossum99d2c252003-06-13 19:28:47 +0000321 memo[id(x)] = y
Guido van Rossum90e05b02003-02-06 18:18:23 +0000322 if listiter is not None:
323 for item in listiter:
324 if deep:
325 item = deepcopy(item, memo)
326 y.append(item)
327 if dictiter is not None:
328 for key, value in dictiter:
329 if deep:
330 key = deepcopy(key, memo)
331 value = deepcopy(value, memo)
332 y[key] = value
Guido van Rossum6cef6d52001-09-28 18:13:29 +0000333 if state:
334 if deep:
Guido van Rossum1e91c142001-12-28 21:33:22 +0000335 state = deepcopy(state, memo)
Guido van Rossum3e3583c2002-06-06 17:41:20 +0000336 if hasattr(y, '__setstate__'):
337 y.__setstate__(state)
338 else:
Guido van Rossumc7557582003-02-06 19:53:22 +0000339 if isinstance(state, tuple) and len(state) == 2:
340 state, slotstate = state
341 else:
342 slotstate = None
343 if state is not None:
344 y.__dict__.update(state)
345 if slotstate is not None:
346 for key, value in slotstate.iteritems():
347 setattr(y, key, value)
Guido van Rossum6cef6d52001-09-28 18:13:29 +0000348 return y
349
Guido van Rossum409780f1995-01-10 00:34:21 +0000350del d
351
352del types
353
Guido van Rossumc5d2d511997-12-07 16:18:22 +0000354# Helper for instance creation without calling __init__
355class _EmptyClass:
356 pass
357
Guido van Rossum409780f1995-01-10 00:34:21 +0000358def _test():
Tim Peters88869f92001-01-14 23:36:06 +0000359 l = [None, 1, 2L, 3.14, 'xyzzy', (1, 2L), [3.14, 'abc'],
360 {'abc': 'ABC'}, (), [], {}]
361 l1 = copy(l)
362 print l1==l
363 l1 = map(copy, l)
364 print l1==l
365 l1 = deepcopy(l)
366 print l1==l
367 class C:
368 def __init__(self, arg=None):
369 self.a = 1
370 self.arg = arg
371 if __name__ == '__main__':
372 import sys
373 file = sys.argv[0]
374 else:
375 file = __file__
376 self.fp = open(file)
377 self.fp.close()
378 def __getstate__(self):
379 return {'a': self.a, 'arg': self.arg}
380 def __setstate__(self, state):
Raymond Hettingere0d49722002-06-02 18:55:56 +0000381 for key, value in state.iteritems():
382 setattr(self, key, value)
Guido van Rossumc06e3ac2003-02-07 17:30:18 +0000383 def __deepcopy__(self, memo=None):
Tim Peters88869f92001-01-14 23:36:06 +0000384 new = self.__class__(deepcopy(self.arg, memo))
385 new.a = self.a
386 return new
387 c = C('argument sketch')
388 l.append(c)
389 l2 = copy(l)
390 print l == l2
391 print l
392 print l2
393 l2 = deepcopy(l)
394 print l == l2
395 print l
396 print l2
397 l.append({l[1]: l, 'xyz': l[2]})
398 l3 = copy(l)
399 import repr
400 print map(repr.repr, l)
401 print map(repr.repr, l1)
402 print map(repr.repr, l2)
403 print map(repr.repr, l3)
404 l3 = deepcopy(l)
405 import repr
406 print map(repr.repr, l)
407 print map(repr.repr, l1)
408 print map(repr.repr, l2)
409 print map(repr.repr, l3)
Guido van Rossum409780f1995-01-10 00:34:21 +0000410
411if __name__ == '__main__':
Tim Peters88869f92001-01-14 23:36:06 +0000412 _test()