blob: f53cd8c58749543941dcc2d89460b040a26308cb [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 Pitrou6e610062009-05-15 17:04:50 +000052import weakref
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +000053from copyreg 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
Berker Peksag27085782018-07-09 23:14:54 +030078 if issubclass(cls, type):
Alexandre Vassalotti5c1c3b42013-12-01 13:25:26 -080079 # treat it as a regular class:
80 return _copy_immutable(x)
81
Guido van Rossumc06e3ac2003-02-07 17:30:18 +000082 copier = getattr(cls, "__copy__", None)
Berker Peksag27085782018-07-09 23:14:54 +030083 if copier is not None:
Guido van Rossumc06e3ac2003-02-07 17:30:18 +000084 return copier(x)
85
86 reductor = dispatch_table.get(cls)
Berker Peksag27085782018-07-09 23:14:54 +030087 if reductor is not None:
Guido van Rossume6908832003-02-19 01:19:28 +000088 rv = reductor(x)
89 else:
90 reductor = getattr(x, "__reduce_ex__", None)
Berker Peksag27085782018-07-09 23:14:54 +030091 if reductor is not None:
Serhiy Storchaka32af7542015-03-24 18:06:42 +020092 rv = reductor(4)
Guido van Rossume6908832003-02-19 01:19:28 +000093 else:
94 reductor = getattr(x, "__reduce__", None)
95 if reductor:
96 rv = reductor()
97 else:
98 raise Error("un(shallow)copyable object of type %s" % cls)
Guido van Rossumc06e3ac2003-02-07 17:30:18 +000099
Serhiy Storchaka818e18d2016-03-06 14:56:57 +0200100 if isinstance(rv, str):
101 return x
102 return _reconstruct(x, None, *rv)
Tim Petersf2715e02003-02-19 02:35:07 +0000103
Guido van Rossumc7557582003-02-06 19:53:22 +0000104
Guido van Rossum409780f1995-01-10 00:34:21 +0000105_copy_dispatch = d = {}
106
Raymond Hettingerf0e35692004-03-08 05:59:33 +0000107def _copy_immutable(x):
Tim Peters88869f92001-01-14 23:36:06 +0000108 return x
Serhiy Storchaka818e18d2016-03-06 14:56:57 +0200109for t in (type(None), int, float, bool, complex, str, tuple,
110 bytes, frozenset, type, range, slice,
111 types.BuiltinFunctionType, type(Ellipsis), type(NotImplemented),
Antoine Pitrou6e610062009-05-15 17:04:50 +0000112 types.FunctionType, weakref.ref):
Raymond Hettingerf0e35692004-03-08 05:59:33 +0000113 d[t] = _copy_immutable
Guido van Rossum13257902007-06-07 23:15:56 +0000114t = getattr(types, "CodeType", None)
115if t is not None:
116 d[t] = _copy_immutable
Guido van Rossum409780f1995-01-10 00:34:21 +0000117
Serhiy Storchaka818e18d2016-03-06 14:56:57 +0200118d[list] = list.copy
119d[dict] = dict.copy
120d[set] = set.copy
121d[bytearray] = bytearray.copy
Guido van Rossum409780f1995-01-10 00:34:21 +0000122
Guido van Rossumf8baad02000-11-27 21:53:14 +0000123if PyStringMap is not None:
Serhiy Storchaka818e18d2016-03-06 14:56:57 +0200124 d[PyStringMap] = PyStringMap.copy
Guido van Rossum409780f1995-01-10 00:34:21 +0000125
Serhiy Storchaka818e18d2016-03-06 14:56:57 +0200126del d, t
Guido van Rossum409780f1995-01-10 00:34:21 +0000127
Guido van Rossumc06e3ac2003-02-07 17:30:18 +0000128def deepcopy(x, memo=None, _nil=[]):
Tim Peters88869f92001-01-14 23:36:06 +0000129 """Deep copy operation on arbitrary Python objects.
Guido van Rossumcc6764c1995-02-09 17:18:10 +0000130
Tim Peters88869f92001-01-14 23:36:06 +0000131 See the module's __doc__ string for more info.
132 """
Guido van Rossumcc6764c1995-02-09 17:18:10 +0000133
Tim Peters88869f92001-01-14 23:36:06 +0000134 if memo is None:
135 memo = {}
Guido van Rossumc06e3ac2003-02-07 17:30:18 +0000136
Tim Peters88869f92001-01-14 23:36:06 +0000137 d = id(x)
Guido van Rossumc06e3ac2003-02-07 17:30:18 +0000138 y = memo.get(d, _nil)
139 if y is not _nil:
140 return y
141
142 cls = type(x)
143
144 copier = _deepcopy_dispatch.get(cls)
Berker Peksag27085782018-07-09 23:14:54 +0300145 if copier is not None:
Guido van Rossumc06e3ac2003-02-07 17:30:18 +0000146 y = copier(x, memo)
147 else:
Berker Peksag27085782018-07-09 23:14:54 +0300148 if issubclass(cls, type):
Guido van Rossume6908832003-02-19 01:19:28 +0000149 y = _deepcopy_atomic(x, memo)
Guido van Rossum6cef6d52001-09-28 18:13:29 +0000150 else:
Guido van Rossume6908832003-02-19 01:19:28 +0000151 copier = getattr(x, "__deepcopy__", None)
Berker Peksag27085782018-07-09 23:14:54 +0300152 if copier is not None:
Guido van Rossume6908832003-02-19 01:19:28 +0000153 y = copier(memo)
154 else:
155 reductor = dispatch_table.get(cls)
156 if reductor:
157 rv = reductor(x)
158 else:
159 reductor = getattr(x, "__reduce_ex__", None)
Berker Peksag27085782018-07-09 23:14:54 +0300160 if reductor is not None:
Serhiy Storchaka32af7542015-03-24 18:06:42 +0200161 rv = reductor(4)
Guido van Rossume6908832003-02-19 01:19:28 +0000162 else:
163 reductor = getattr(x, "__reduce__", None)
164 if reductor:
165 rv = reductor()
166 else:
167 raise Error(
168 "un(deep)copyable object of type %s" % cls)
Serhiy Storchaka818e18d2016-03-06 14:56:57 +0200169 if isinstance(rv, str):
170 y = x
171 else:
172 y = _reconstruct(x, memo, *rv)
Guido van Rossumc06e3ac2003-02-07 17:30:18 +0000173
Benjamin Petersone90ec362011-06-27 16:22:46 -0500174 # If is its own copy, don't memoize.
175 if y is not x:
176 memo[d] = y
177 _keep_alive(x, memo) # Make sure x lives at least as long as d
Tim Peters88869f92001-01-14 23:36:06 +0000178 return y
Guido van Rossum409780f1995-01-10 00:34:21 +0000179
180_deepcopy_dispatch = d = {}
181
182def _deepcopy_atomic(x, memo):
Tim Peters88869f92001-01-14 23:36:06 +0000183 return x
Raymond Hettingerf7153662005-02-07 14:16:21 +0000184d[type(None)] = _deepcopy_atomic
Christian Heimescc47b052008-03-25 14:56:36 +0000185d[type(Ellipsis)] = _deepcopy_atomic
Serhiy Storchaka818e18d2016-03-06 14:56:57 +0200186d[type(NotImplemented)] = _deepcopy_atomic
Raymond Hettingerf7153662005-02-07 14:16:21 +0000187d[int] = _deepcopy_atomic
Raymond Hettingerf7153662005-02-07 14:16:21 +0000188d[float] = _deepcopy_atomic
189d[bool] = _deepcopy_atomic
Serhiy Storchaka818e18d2016-03-06 14:56:57 +0200190d[complex] = _deepcopy_atomic
Guido van Rossum98297ee2007-11-06 21:34:58 +0000191d[bytes] = _deepcopy_atomic
Raymond Hettingerf7153662005-02-07 14:16:21 +0000192d[str] = _deepcopy_atomic
Berker Peksag27085782018-07-09 23:14:54 +0300193d[types.CodeType] = _deepcopy_atomic
Raymond Hettingerf7153662005-02-07 14:16:21 +0000194d[type] = _deepcopy_atomic
Martin v. Löwisba8f5ff2003-06-14 07:10:06 +0000195d[types.BuiltinFunctionType] = _deepcopy_atomic
Guido van Rossum1968ad32006-02-25 22:38:04 +0000196d[types.FunctionType] = _deepcopy_atomic
Antoine Pitrou6e610062009-05-15 17:04:50 +0000197d[weakref.ref] = _deepcopy_atomic
Guido van Rossum409780f1995-01-10 00:34:21 +0000198
Serhiy Storchaka818e18d2016-03-06 14:56:57 +0200199def _deepcopy_list(x, memo, deepcopy=deepcopy):
Tim Peters88869f92001-01-14 23:36:06 +0000200 y = []
201 memo[id(x)] = y
Serhiy Storchaka818e18d2016-03-06 14:56:57 +0200202 append = y.append
Tim Peters88869f92001-01-14 23:36:06 +0000203 for a in x:
Serhiy Storchaka818e18d2016-03-06 14:56:57 +0200204 append(deepcopy(a, memo))
Tim Peters88869f92001-01-14 23:36:06 +0000205 return y
Raymond Hettingerf7153662005-02-07 14:16:21 +0000206d[list] = _deepcopy_list
Guido van Rossum409780f1995-01-10 00:34:21 +0000207
Serhiy Storchaka818e18d2016-03-06 14:56:57 +0200208def _deepcopy_tuple(x, memo, deepcopy=deepcopy):
Benjamin Peterson4ce5f3f2014-05-03 20:22:00 -0400209 y = [deepcopy(a, memo) for a in x]
Benjamin Petersone90ec362011-06-27 16:22:46 -0500210 # We're not going to put the tuple in the memo, but it's still important we
211 # check for it, in case the tuple contains recursive mutable structures.
Tim Peters88869f92001-01-14 23:36:06 +0000212 try:
Benjamin Petersone90ec362011-06-27 16:22:46 -0500213 return memo[id(x)]
Tim Peters88869f92001-01-14 23:36:06 +0000214 except KeyError:
215 pass
Benjamin Peterson4ce5f3f2014-05-03 20:22:00 -0400216 for k, j in zip(x, y):
217 if k is not j:
Tim Peters88869f92001-01-14 23:36:06 +0000218 y = tuple(y)
219 break
220 else:
221 y = x
Tim Peters88869f92001-01-14 23:36:06 +0000222 return y
Raymond Hettingerf7153662005-02-07 14:16:21 +0000223d[tuple] = _deepcopy_tuple
Guido van Rossum409780f1995-01-10 00:34:21 +0000224
Serhiy Storchaka818e18d2016-03-06 14:56:57 +0200225def _deepcopy_dict(x, memo, deepcopy=deepcopy):
Tim Peters88869f92001-01-14 23:36:06 +0000226 y = {}
227 memo[id(x)] = y
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000228 for key, value in x.items():
Raymond Hettingere0d49722002-06-02 18:55:56 +0000229 y[deepcopy(key, memo)] = deepcopy(value, memo)
Tim Peters88869f92001-01-14 23:36:06 +0000230 return y
Raymond Hettingerf7153662005-02-07 14:16:21 +0000231d[dict] = _deepcopy_dict
Guido van Rossumf8baad02000-11-27 21:53:14 +0000232if PyStringMap is not None:
233 d[PyStringMap] = _deepcopy_dict
Guido van Rossum409780f1995-01-10 00:34:21 +0000234
Antoine Pitrou1fc0d2b2009-11-28 15:58:27 +0000235def _deepcopy_method(x, memo): # Copy instance methods
236 return type(x)(x.__func__, deepcopy(x.__self__, memo))
Serhiy Storchaka818e18d2016-03-06 14:56:57 +0200237d[types.MethodType] = _deepcopy_method
238
239del d
Antoine Pitrou1fc0d2b2009-11-28 15:58:27 +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
Serhiy Storchaka818e18d2016-03-06 14:56:57 +0200257def _reconstruct(x, memo, func, args,
258 state=None, listiter=None, dictiter=None,
259 deepcopy=deepcopy):
260 deep = memo is not None
261 if deep and args:
262 args = (deepcopy(arg, memo) for arg in args)
263 y = func(*args)
Guido van Rossum6cef6d52001-09-28 18:13:29 +0000264 if deep:
Serhiy Storchaka818e18d2016-03-06 14:56:57 +0200265 memo[id(x)] = y
Antoine Pitrou3941a8f2010-09-04 17:40:21 +0000266
Serhiy Storchakacbbec1c2015-11-30 17:20:02 +0200267 if state is not None:
Guido van Rossum6cef6d52001-09-28 18:13:29 +0000268 if deep:
Guido van Rossum1e91c142001-12-28 21:33:22 +0000269 state = deepcopy(state, memo)
Guido van Rossum3e3583c2002-06-06 17:41:20 +0000270 if hasattr(y, '__setstate__'):
271 y.__setstate__(state)
272 else:
Guido van Rossumc7557582003-02-06 19:53:22 +0000273 if isinstance(state, tuple) and len(state) == 2:
274 state, slotstate = state
275 else:
276 slotstate = None
277 if state is not None:
278 y.__dict__.update(state)
279 if slotstate is not None:
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000280 for key, value in slotstate.items():
Guido van Rossumc7557582003-02-06 19:53:22 +0000281 setattr(y, key, value)
Antoine Pitrou3941a8f2010-09-04 17:40:21 +0000282
283 if listiter is not None:
Serhiy Storchaka818e18d2016-03-06 14:56:57 +0200284 if deep:
285 for item in listiter:
Antoine Pitrou3941a8f2010-09-04 17:40:21 +0000286 item = deepcopy(item, memo)
Serhiy Storchaka818e18d2016-03-06 14:56:57 +0200287 y.append(item)
288 else:
289 for item in listiter:
290 y.append(item)
Antoine Pitrou3941a8f2010-09-04 17:40:21 +0000291 if dictiter is not None:
Serhiy Storchaka818e18d2016-03-06 14:56:57 +0200292 if deep:
293 for key, value in dictiter:
Antoine Pitrou3941a8f2010-09-04 17:40:21 +0000294 key = deepcopy(key, memo)
295 value = deepcopy(value, memo)
Serhiy Storchaka818e18d2016-03-06 14:56:57 +0200296 y[key] = value
297 else:
298 for key, value in dictiter:
299 y[key] = value
Guido van Rossum6cef6d52001-09-28 18:13:29 +0000300 return y
301
Serhiy Storchaka818e18d2016-03-06 14:56:57 +0200302del types, weakref, PyStringMap