copy.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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 any
  29. 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. __all__ = ["Error", "copy", "deepcopy"]
  42. def copy(x):
  43. """Shallow copy operation on arbitrary Python objects.
  44. See the module's __doc__ string for more info.
  45. """
  46. cls = type(x)
  47. copier = _copy_dispatch.get(cls)
  48. if copier:
  49. return copier(x)
  50. if issubclass(cls, type):
  51. # treat it as a regular class:
  52. return _copy_immutable(x)
  53. copier = getattr(cls, "__copy__", None)
  54. if copier is not None:
  55. return copier(x)
  56. reductor = dispatch_table.get(cls)
  57. if reductor is not None:
  58. rv = reductor(x)
  59. else:
  60. reductor = getattr(x, "__reduce_ex__", None)
  61. if reductor is not None:
  62. rv = reductor(4)
  63. else:
  64. reductor = getattr(x, "__reduce__", None)
  65. if reductor:
  66. rv = reductor()
  67. else:
  68. raise Error("un(shallow)copyable object of type %s" % cls)
  69. if isinstance(rv, str):
  70. return x
  71. return _reconstruct(x, None, *rv)
  72. _copy_dispatch = d = {}
  73. def _copy_immutable(x):
  74. return x
  75. for t in (types.NoneType, int, float, bool, complex, str, tuple,
  76. bytes, frozenset, type, range, slice, property,
  77. types.BuiltinFunctionType, types.EllipsisType,
  78. types.NotImplementedType, types.FunctionType, types.CodeType,
  79. weakref.ref):
  80. d[t] = _copy_immutable
  81. d[list] = list.copy
  82. d[dict] = dict.copy
  83. d[set] = set.copy
  84. d[bytearray] = bytearray.copy
  85. del d, t
  86. def deepcopy(x, memo=None, _nil=[]):
  87. """Deep copy operation on arbitrary Python objects.
  88. See the module's __doc__ string for more info.
  89. """
  90. if memo is None:
  91. memo = {}
  92. d = id(x)
  93. y = memo.get(d, _nil)
  94. if y is not _nil:
  95. return y
  96. cls = type(x)
  97. copier = _deepcopy_dispatch.get(cls)
  98. if copier is not None:
  99. y = copier(x, memo)
  100. else:
  101. if issubclass(cls, type):
  102. y = _deepcopy_atomic(x, memo)
  103. else:
  104. copier = getattr(x, "__deepcopy__", None)
  105. if copier is not None:
  106. y = copier(memo)
  107. else:
  108. reductor = dispatch_table.get(cls)
  109. if reductor:
  110. rv = reductor(x)
  111. else:
  112. reductor = getattr(x, "__reduce_ex__", None)
  113. if reductor is not None:
  114. rv = reductor(4)
  115. else:
  116. reductor = getattr(x, "__reduce__", None)
  117. if reductor:
  118. rv = reductor()
  119. else:
  120. raise Error(
  121. "un(deep)copyable object of type %s" % cls)
  122. if isinstance(rv, str):
  123. y = x
  124. else:
  125. y = _reconstruct(x, memo, *rv)
  126. # If is its own copy, don't memoize.
  127. if y is not x:
  128. memo[d] = y
  129. _keep_alive(x, memo) # Make sure x lives at least as long as d
  130. return y
  131. _deepcopy_dispatch = d = {}
  132. def _deepcopy_atomic(x, memo):
  133. return x
  134. d[types.NoneType] = _deepcopy_atomic
  135. d[types.EllipsisType] = _deepcopy_atomic
  136. d[types.NotImplementedType] = _deepcopy_atomic
  137. d[int] = _deepcopy_atomic
  138. d[float] = _deepcopy_atomic
  139. d[bool] = _deepcopy_atomic
  140. d[complex] = _deepcopy_atomic
  141. d[bytes] = _deepcopy_atomic
  142. d[str] = _deepcopy_atomic
  143. d[types.CodeType] = _deepcopy_atomic
  144. d[type] = _deepcopy_atomic
  145. d[range] = _deepcopy_atomic
  146. d[types.BuiltinFunctionType] = _deepcopy_atomic
  147. d[types.FunctionType] = _deepcopy_atomic
  148. d[weakref.ref] = _deepcopy_atomic
  149. d[property] = _deepcopy_atomic
  150. def _deepcopy_list(x, memo, deepcopy=deepcopy):
  151. y = []
  152. memo[id(x)] = y
  153. append = y.append
  154. for a in x:
  155. append(deepcopy(a, memo))
  156. return y
  157. d[list] = _deepcopy_list
  158. def _deepcopy_tuple(x, memo, deepcopy=deepcopy):
  159. y = [deepcopy(a, memo) for a in x]
  160. # We're not going to put the tuple in the memo, but it's still important we
  161. # check for it, in case the tuple contains recursive mutable structures.
  162. try:
  163. return memo[id(x)]
  164. except KeyError:
  165. pass
  166. for k, j in zip(x, y):
  167. if k is not j:
  168. y = tuple(y)
  169. break
  170. else:
  171. y = x
  172. return y
  173. d[tuple] = _deepcopy_tuple
  174. def _deepcopy_dict(x, memo, deepcopy=deepcopy):
  175. y = {}
  176. memo[id(x)] = y
  177. for key, value in x.items():
  178. y[deepcopy(key, memo)] = deepcopy(value, memo)
  179. return y
  180. d[dict] = _deepcopy_dict
  181. def _deepcopy_method(x, memo): # Copy instance methods
  182. return type(x)(x.__func__, deepcopy(x.__self__, memo))
  183. d[types.MethodType] = _deepcopy_method
  184. del d
  185. def _keep_alive(x, memo):
  186. """Keeps a reference to the object x in the memo.
  187. Because we remember objects by their id, we have
  188. to assure that possibly temporary objects are kept
  189. alive by referencing them.
  190. We store a reference at the id of the memo, which should
  191. normally not be used unless someone tries to deepcopy
  192. the memo itself...
  193. """
  194. try:
  195. memo[id(memo)].append(x)
  196. except KeyError:
  197. # aha, this is the first one :-)
  198. memo[id(memo)]=[x]
  199. def _reconstruct(x, memo, func, args,
  200. state=None, listiter=None, dictiter=None,
  201. *, deepcopy=deepcopy):
  202. deep = memo is not None
  203. if deep and args:
  204. args = (deepcopy(arg, memo) for arg in args)
  205. y = func(*args)
  206. if deep:
  207. memo[id(x)] = y
  208. if state is not None:
  209. if deep:
  210. state = deepcopy(state, memo)
  211. if hasattr(y, '__setstate__'):
  212. y.__setstate__(state)
  213. else:
  214. if isinstance(state, tuple) and len(state) == 2:
  215. state, slotstate = state
  216. else:
  217. slotstate = None
  218. if state is not None:
  219. y.__dict__.update(state)
  220. if slotstate is not None:
  221. for key, value in slotstate.items():
  222. setattr(y, key, value)
  223. if listiter is not None:
  224. if deep:
  225. for item in listiter:
  226. item = deepcopy(item, memo)
  227. y.append(item)
  228. else:
  229. for item in listiter:
  230. y.append(item)
  231. if dictiter is not None:
  232. if deep:
  233. for key, value in dictiter:
  234. key = deepcopy(key, memo)
  235. value = deepcopy(value, memo)
  236. y[key] = value
  237. else:
  238. for key, value in dictiter:
  239. y[key] = value
  240. return y
  241. del types, weakref