Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

copy.py 8.6 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
  1. """Generic (shallow and deep) copying operations.
  2. Interface summary:
  3. import copy
  4. x = copy.copy(y) # make a shallow copy of y
  5. x = copy.deepcopy(y) # make a deep copy of y
  6. For module specific errors, copy.Error is raised.
  7. The difference between shallow and deep copying is only relevant for
  8. compound objects (objects that contain other objects, like lists or
  9. class instances).
  10. - A shallow copy constructs a new compound object and then (to the
  11. extent possible) inserts *the same objects* into it that the
  12. original contains.
  13. - A deep copy constructs a new compound object and then, recursively,
  14. inserts *copies* into it of the objects found in the original.
  15. Two problems often exist with deep copy operations that don't exist
  16. with shallow copy operations:
  17. a) recursive objects (compound objects that, directly or indirectly,
  18. contain a reference to themselves) may cause a recursive loop
  19. b) because deep copy copies *everything* it may copy too much, e.g.
  20. administrative data structures that should be shared even between
  21. copies
  22. Python's deep copy operation avoids these problems by:
  23. a) keeping a table of objects already copied during the current
  24. copying pass
  25. b) letting user-defined classes override the copying operation or the
  26. set of components copied
  27. This version does not copy types like module, class, function, method,
  28. nor stack trace, stack frame, nor file, socket, window, nor array, nor
  29. any similar types.
  30. Classes can use the same interfaces to control copying that they use
  31. to control pickling: they can define methods called __getinitargs__(),
  32. __getstate__() and __setstate__(). See the documentation for module
  33. "pickle" for information on these methods.
  34. """
  35. import types
  36. import weakref
  37. from copyreg import dispatch_table
  38. class Error(Exception):
  39. pass
  40. error = Error # backward compatibility
  41. try:
  42. from org.python.core import PyStringMap
  43. except ImportError:
  44. PyStringMap = None
  45. __all__ = ["Error", "copy", "deepcopy"]
  46. def copy(x):
  47. """Shallow copy operation on arbitrary Python objects.
  48. See the module's __doc__ string for more info.
  49. """
  50. cls = type(x)
  51. copier = _copy_dispatch.get(cls)
  52. if copier:
  53. return copier(x)
  54. try:
  55. issc = issubclass(cls, type)
  56. except TypeError: # cls is not a class
  57. issc = False
  58. if issc:
  59. # treat it as a regular class:
  60. return _copy_immutable(x)
  61. copier = getattr(cls, "__copy__", None)
  62. if copier:
  63. return copier(x)
  64. reductor = dispatch_table.get(cls)
  65. if reductor:
  66. rv = reductor(x)
  67. else:
  68. reductor = getattr(x, "__reduce_ex__", None)
  69. if reductor:
  70. rv = reductor(4)
  71. else:
  72. reductor = getattr(x, "__reduce__", None)
  73. if reductor:
  74. rv = reductor()
  75. else:
  76. raise Error("un(shallow)copyable object of type %s" % cls)
  77. if isinstance(rv, str):
  78. return x
  79. return _reconstruct(x, None, *rv)
  80. _copy_dispatch = d = {}
  81. def _copy_immutable(x):
  82. return x
  83. for t in (type(None), int, float, bool, complex, str, tuple,
  84. bytes, frozenset, type, range, slice,
  85. types.BuiltinFunctionType, type(Ellipsis), type(NotImplemented),
  86. types.FunctionType, weakref.ref):
  87. d[t] = _copy_immutable
  88. t = getattr(types, "CodeType", None)
  89. if t is not None:
  90. d[t] = _copy_immutable
  91. d[list] = list.copy
  92. d[dict] = dict.copy
  93. d[set] = set.copy
  94. d[bytearray] = bytearray.copy
  95. if PyStringMap is not None:
  96. d[PyStringMap] = PyStringMap.copy
  97. del d, t
  98. def deepcopy(x, memo=None, _nil=[]):
  99. """Deep copy operation on arbitrary Python objects.
  100. See the module's __doc__ string for more info.
  101. """
  102. if memo is None:
  103. memo = {}
  104. d = id(x)
  105. y = memo.get(d, _nil)
  106. if y is not _nil:
  107. return y
  108. cls = type(x)
  109. copier = _deepcopy_dispatch.get(cls)
  110. if copier:
  111. y = copier(x, memo)
  112. else:
  113. try:
  114. issc = issubclass(cls, type)
  115. except TypeError: # cls is not a class (old Boost; see SF #502085)
  116. issc = 0
  117. if issc:
  118. y = _deepcopy_atomic(x, memo)
  119. else:
  120. copier = getattr(x, "__deepcopy__", None)
  121. if copier:
  122. y = copier(memo)
  123. else:
  124. reductor = dispatch_table.get(cls)
  125. if reductor:
  126. rv = reductor(x)
  127. else:
  128. reductor = getattr(x, "__reduce_ex__", None)
  129. if reductor:
  130. rv = reductor(4)
  131. else:
  132. reductor = getattr(x, "__reduce__", None)
  133. if reductor:
  134. rv = reductor()
  135. else:
  136. raise Error(
  137. "un(deep)copyable object of type %s" % cls)
  138. if isinstance(rv, str):
  139. y = x
  140. else:
  141. y = _reconstruct(x, memo, *rv)
  142. # If is its own copy, don't memoize.
  143. if y is not x:
  144. memo[d] = y
  145. _keep_alive(x, memo) # Make sure x lives at least as long as d
  146. return y
  147. _deepcopy_dispatch = d = {}
  148. def _deepcopy_atomic(x, memo):
  149. return x
  150. d[type(None)] = _deepcopy_atomic
  151. d[type(Ellipsis)] = _deepcopy_atomic
  152. d[type(NotImplemented)] = _deepcopy_atomic
  153. d[int] = _deepcopy_atomic
  154. d[float] = _deepcopy_atomic
  155. d[bool] = _deepcopy_atomic
  156. d[complex] = _deepcopy_atomic
  157. d[bytes] = _deepcopy_atomic
  158. d[str] = _deepcopy_atomic
  159. try:
  160. d[types.CodeType] = _deepcopy_atomic
  161. except AttributeError:
  162. pass
  163. d[type] = _deepcopy_atomic
  164. d[types.BuiltinFunctionType] = _deepcopy_atomic
  165. d[types.FunctionType] = _deepcopy_atomic
  166. d[weakref.ref] = _deepcopy_atomic
  167. def _deepcopy_list(x, memo, deepcopy=deepcopy):
  168. y = []
  169. memo[id(x)] = y
  170. append = y.append
  171. for a in x:
  172. append(deepcopy(a, memo))
  173. return y
  174. d[list] = _deepcopy_list
  175. def _deepcopy_tuple(x, memo, deepcopy=deepcopy):
  176. y = [deepcopy(a, memo) for a in x]
  177. # We're not going to put the tuple in the memo, but it's still important we
  178. # check for it, in case the tuple contains recursive mutable structures.
  179. try:
  180. return memo[id(x)]
  181. except KeyError:
  182. pass
  183. for k, j in zip(x, y):
  184. if k is not j:
  185. y = tuple(y)
  186. break
  187. else:
  188. y = x
  189. return y
  190. d[tuple] = _deepcopy_tuple
  191. def _deepcopy_dict(x, memo, deepcopy=deepcopy):
  192. y = {}
  193. memo[id(x)] = y
  194. for key, value in x.items():
  195. y[deepcopy(key, memo)] = deepcopy(value, memo)
  196. return y
  197. d[dict] = _deepcopy_dict
  198. if PyStringMap is not None:
  199. d[PyStringMap] = _deepcopy_dict
  200. def _deepcopy_method(x, memo): # Copy instance methods
  201. return type(x)(x.__func__, deepcopy(x.__self__, memo))
  202. d[types.MethodType] = _deepcopy_method
  203. del d
  204. def _keep_alive(x, memo):
  205. """Keeps a reference to the object x in the memo.
  206. Because we remember objects by their id, we have
  207. to assure that possibly temporary objects are kept
  208. alive by referencing them.
  209. We store a reference at the id of the memo, which should
  210. normally not be used unless someone tries to deepcopy
  211. the memo itself...
  212. """
  213. try:
  214. memo[id(memo)].append(x)
  215. except KeyError:
  216. # aha, this is the first one :-)
  217. memo[id(memo)]=[x]
  218. def _reconstruct(x, memo, func, args,
  219. state=None, listiter=None, dictiter=None,
  220. deepcopy=deepcopy):
  221. deep = memo is not None
  222. if deep and args:
  223. args = (deepcopy(arg, memo) for arg in args)
  224. y = func(*args)
  225. if deep:
  226. memo[id(x)] = y
  227. if state is not None:
  228. if deep:
  229. state = deepcopy(state, memo)
  230. if hasattr(y, '__setstate__'):
  231. y.__setstate__(state)
  232. else:
  233. if isinstance(state, tuple) and len(state) == 2:
  234. state, slotstate = state
  235. else:
  236. slotstate = None
  237. if state is not None:
  238. y.__dict__.update(state)
  239. if slotstate is not None:
  240. for key, value in slotstate.items():
  241. setattr(y, key, value)
  242. if listiter is not None:
  243. if deep:
  244. for item in listiter:
  245. item = deepcopy(item, memo)
  246. y.append(item)
  247. else:
  248. for item in listiter:
  249. y.append(item)
  250. if dictiter is not None:
  251. if deep:
  252. for key, value in dictiter:
  253. key = deepcopy(key, memo)
  254. value = deepcopy(value, memo)
  255. y[key] = value
  256. else:
  257. for key, value in dictiter:
  258. y[key] = value
  259. return y
  260. del types, weakref, PyStringMap
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...