copy.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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, property,
  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. d[property] = _deepcopy_atomic
  168. def _deepcopy_list(x, memo, deepcopy=deepcopy):
  169. y = []
  170. memo[id(x)] = y
  171. append = y.append
  172. for a in x:
  173. append(deepcopy(a, memo))
  174. return y
  175. d[list] = _deepcopy_list
  176. def _deepcopy_tuple(x, memo, deepcopy=deepcopy):
  177. y = [deepcopy(a, memo) for a in x]
  178. # We're not going to put the tuple in the memo, but it's still important we
  179. # check for it, in case the tuple contains recursive mutable structures.
  180. try:
  181. return memo[id(x)]
  182. except KeyError:
  183. pass
  184. for k, j in zip(x, y):
  185. if k is not j:
  186. y = tuple(y)
  187. break
  188. else:
  189. y = x
  190. return y
  191. d[tuple] = _deepcopy_tuple
  192. def _deepcopy_dict(x, memo, deepcopy=deepcopy):
  193. y = {}
  194. memo[id(x)] = y
  195. for key, value in x.items():
  196. y[deepcopy(key, memo)] = deepcopy(value, memo)
  197. return y
  198. d[dict] = _deepcopy_dict
  199. if PyStringMap is not None:
  200. d[PyStringMap] = _deepcopy_dict
  201. def _deepcopy_method(x, memo): # Copy instance methods
  202. return type(x)(x.__func__, deepcopy(x.__self__, memo))
  203. d[types.MethodType] = _deepcopy_method
  204. del d
  205. def _keep_alive(x, memo):
  206. """Keeps a reference to the object x in the memo.
  207. Because we remember objects by their id, we have
  208. to assure that possibly temporary objects are kept
  209. alive by referencing them.
  210. We store a reference at the id of the memo, which should
  211. normally not be used unless someone tries to deepcopy
  212. the memo itself...
  213. """
  214. try:
  215. memo[id(memo)].append(x)
  216. except KeyError:
  217. # aha, this is the first one :-)
  218. memo[id(memo)]=[x]
  219. def _reconstruct(x, memo, func, args,
  220. state=None, listiter=None, dictiter=None,
  221. deepcopy=deepcopy):
  222. deep = memo is not None
  223. if deep and args:
  224. args = (deepcopy(arg, memo) for arg in args)
  225. y = func(*args)
  226. if deep:
  227. memo[id(x)] = y
  228. if state is not None:
  229. if deep:
  230. state = deepcopy(state, memo)
  231. if hasattr(y, '__setstate__'):
  232. y.__setstate__(state)
  233. else:
  234. if isinstance(state, tuple) and len(state) == 2:
  235. state, slotstate = state
  236. else:
  237. slotstate = None
  238. if state is not None:
  239. y.__dict__.update(state)
  240. if slotstate is not None:
  241. for key, value in slotstate.items():
  242. setattr(y, key, value)
  243. if listiter is not None:
  244. if deep:
  245. for item in listiter:
  246. item = deepcopy(item, memo)
  247. y.append(item)
  248. else:
  249. for item in listiter:
  250. y.append(item)
  251. if dictiter is not None:
  252. if deep:
  253. for key, value in dictiter:
  254. key = deepcopy(key, memo)
  255. value = deepcopy(value, memo)
  256. y[key] = value
  257. else:
  258. for key, value in dictiter:
  259. y[key] = value
  260. return y
  261. del types, weakref, PyStringMap