copy.py 8.7 KB

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