copy.py 8.4 KB

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