copy.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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. from copy_reg import dispatch_table
  37. class Error(Exception):
  38. pass
  39. error = Error # backward compatibility
  40. try:
  41. from org.python.core import PyStringMap
  42. except ImportError:
  43. PyStringMap = None
  44. __all__ = ["Error", "copy", "deepcopy"]
  45. import inspect
  46. def _getspecial(cls, name):
  47. for basecls in inspect.getmro(cls):
  48. try:
  49. return basecls.__dict__[name]
  50. except:
  51. pass
  52. else:
  53. return None
  54. def copy(x):
  55. """Shallow copy operation on arbitrary Python objects.
  56. See the module's __doc__ string for more info.
  57. """
  58. cls = type(x)
  59. copier = _copy_dispatch.get(cls)
  60. if copier:
  61. return copier(x)
  62. copier = _getspecial(cls, "__copy__")
  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(2)
  72. else:
  73. reductor = getattr(x, "__reduce__", None)
  74. if reductor:
  75. rv = reductor()
  76. else:
  77. copier = getattr(x, "__copy__", None)
  78. if copier:
  79. return copier()
  80. raise Error("un(shallow)copyable object of type %s" % cls)
  81. return _reconstruct(x, rv, 0)
  82. _copy_dispatch = d = {}
  83. def _copy_immutable(x):
  84. return x
  85. for t in (types.NoneType, int, long, float, bool, str, tuple,
  86. frozenset, type, xrange, types.ClassType,
  87. types.BuiltinFunctionType):
  88. d[t] = _copy_immutable
  89. for name in ("ComplexType", "UnicodeType", "CodeType"):
  90. t = getattr(types, name, None)
  91. if t is not None:
  92. d[t] = _copy_immutable
  93. def _copy_with_constructor(x):
  94. return type(x)(x)
  95. for t in (list, dict, set):
  96. d[t] = _copy_with_constructor
  97. def _copy_with_copy_method(x):
  98. return x.copy()
  99. if PyStringMap is not None:
  100. d[PyStringMap] = _copy_with_copy_method
  101. def _copy_inst(x):
  102. if hasattr(x, '__copy__'):
  103. return x.__copy__()
  104. if hasattr(x, '__getinitargs__'):
  105. args = x.__getinitargs__()
  106. y = x.__class__(*args)
  107. else:
  108. y = _EmptyClass()
  109. y.__class__ = x.__class__
  110. if hasattr(x, '__getstate__'):
  111. state = x.__getstate__()
  112. else:
  113. state = x.__dict__
  114. if hasattr(y, '__setstate__'):
  115. y.__setstate__(state)
  116. else:
  117. y.__dict__.update(state)
  118. return y
  119. d[types.InstanceType] = _copy_inst
  120. del d
  121. def deepcopy(x, memo=None, _nil=[]):
  122. """Deep copy operation on arbitrary Python objects.
  123. See the module's __doc__ string for more info.
  124. """
  125. if memo is None:
  126. memo = {}
  127. d = id(x)
  128. y = memo.get(d, _nil)
  129. if y is not _nil:
  130. return y
  131. cls = type(x)
  132. copier = _deepcopy_dispatch.get(cls)
  133. if copier:
  134. y = copier(x, memo)
  135. else:
  136. try:
  137. issc = issubclass(cls, type)
  138. except TypeError: # cls is not a class (old Boost; see SF #502085)
  139. issc = 0
  140. if issc:
  141. y = _deepcopy_atomic(x, memo)
  142. else:
  143. copier = _getspecial(cls, "__deepcopy__")
  144. if copier:
  145. y = copier(x, memo)
  146. else:
  147. reductor = dispatch_table.get(cls)
  148. if reductor:
  149. rv = reductor(x)
  150. else:
  151. reductor = getattr(x, "__reduce_ex__", None)
  152. if reductor:
  153. rv = reductor(2)
  154. else:
  155. reductor = getattr(x, "__reduce__", None)
  156. if reductor:
  157. rv = reductor()
  158. else:
  159. copier = getattr(x, "__deepcopy__", None)
  160. if copier:
  161. return copier(memo)
  162. raise Error(
  163. "un(deep)copyable object of type %s" % cls)
  164. y = _reconstruct(x, rv, 1, memo)
  165. memo[d] = y
  166. _keep_alive(x, memo) # Make sure x lives at least as long as d
  167. return y
  168. _deepcopy_dispatch = d = {}
  169. def _deepcopy_atomic(x, memo):
  170. return x
  171. d[types.NoneType] = _deepcopy_atomic
  172. d[types.IntType] = _deepcopy_atomic
  173. d[types.LongType] = _deepcopy_atomic
  174. d[types.FloatType] = _deepcopy_atomic
  175. d[types.BooleanType] = _deepcopy_atomic
  176. try:
  177. d[types.ComplexType] = _deepcopy_atomic
  178. except AttributeError:
  179. pass
  180. d[types.StringType] = _deepcopy_atomic
  181. try:
  182. d[types.UnicodeType] = _deepcopy_atomic
  183. except AttributeError:
  184. pass
  185. try:
  186. d[types.CodeType] = _deepcopy_atomic
  187. except AttributeError:
  188. pass
  189. d[types.TypeType] = _deepcopy_atomic
  190. d[types.XRangeType] = _deepcopy_atomic
  191. d[types.ClassType] = _deepcopy_atomic
  192. d[types.BuiltinFunctionType] = _deepcopy_atomic
  193. def _deepcopy_list(x, memo):
  194. y = []
  195. memo[id(x)] = y
  196. for a in x:
  197. y.append(deepcopy(a, memo))
  198. return y
  199. d[types.ListType] = _deepcopy_list
  200. def _deepcopy_tuple(x, memo):
  201. y = []
  202. for a in x:
  203. y.append(deepcopy(a, memo))
  204. d = id(x)
  205. try:
  206. return memo[d]
  207. except KeyError:
  208. pass
  209. for i in range(len(x)):
  210. if x[i] is not y[i]:
  211. y = tuple(y)
  212. break
  213. else:
  214. y = x
  215. memo[d] = y
  216. return y
  217. d[types.TupleType] = _deepcopy_tuple
  218. def _deepcopy_dict(x, memo):
  219. y = {}
  220. memo[id(x)] = y
  221. for key, value in x.iteritems():
  222. y[deepcopy(key, memo)] = deepcopy(value, memo)
  223. return y
  224. d[types.DictionaryType] = _deepcopy_dict
  225. if PyStringMap is not None:
  226. d[PyStringMap] = _deepcopy_dict
  227. def _keep_alive(x, memo):
  228. """Keeps a reference to the object x in the memo.
  229. Because we remember objects by their id, we have
  230. to assure that possibly temporary objects are kept
  231. alive by referencing them.
  232. We store a reference at the id of the memo, which should
  233. normally not be used unless someone tries to deepcopy
  234. the memo itself...
  235. """
  236. try:
  237. memo[id(memo)].append(x)
  238. except KeyError:
  239. # aha, this is the first one :-)
  240. memo[id(memo)]=[x]
  241. def _deepcopy_inst(x, memo):
  242. if hasattr(x, '__deepcopy__'):
  243. return x.__deepcopy__(memo)
  244. if hasattr(x, '__getinitargs__'):
  245. args = x.__getinitargs__()
  246. args = deepcopy(args, memo)
  247. y = x.__class__(*args)
  248. else:
  249. y = _EmptyClass()
  250. y.__class__ = x.__class__
  251. memo[id(x)] = y
  252. if hasattr(x, '__getstate__'):
  253. state = x.__getstate__()
  254. else:
  255. state = x.__dict__
  256. state = deepcopy(state, memo)
  257. if hasattr(y, '__setstate__'):
  258. y.__setstate__(state)
  259. else:
  260. y.__dict__.update(state)
  261. return y
  262. d[types.InstanceType] = _deepcopy_inst
  263. def _reconstruct(x, info, deep, memo=None):
  264. if isinstance(info, str):
  265. return x
  266. assert isinstance(info, tuple)
  267. if memo is None:
  268. memo = {}
  269. n = len(info)
  270. assert n in (2, 3, 4, 5)
  271. callable, args = info[:2]
  272. if n > 2:
  273. state = info[2]
  274. else:
  275. state = {}
  276. if n > 3:
  277. listiter = info[3]
  278. else:
  279. listiter = None
  280. if n > 4:
  281. dictiter = info[4]
  282. else:
  283. dictiter = None
  284. if deep:
  285. args = deepcopy(args, memo)
  286. y = callable(*args)
  287. memo[id(x)] = y
  288. if listiter is not None:
  289. for item in listiter:
  290. if deep:
  291. item = deepcopy(item, memo)
  292. y.append(item)
  293. if dictiter is not None:
  294. for key, value in dictiter:
  295. if deep:
  296. key = deepcopy(key, memo)
  297. value = deepcopy(value, memo)
  298. y[key] = value
  299. if state:
  300. if deep:
  301. state = deepcopy(state, memo)
  302. if hasattr(y, '__setstate__'):
  303. y.__setstate__(state)
  304. else:
  305. if isinstance(state, tuple) and len(state) == 2:
  306. state, slotstate = state
  307. else:
  308. slotstate = None
  309. if state is not None:
  310. y.__dict__.update(state)
  311. if slotstate is not None:
  312. for key, value in slotstate.iteritems():
  313. setattr(y, key, value)
  314. return y
  315. del d
  316. del types
  317. # Helper for instance creation without calling __init__
  318. class _EmptyClass:
  319. pass
  320. def _test():
  321. l = [None, 1, 2L, 3.14, 'xyzzy', (1, 2L), [3.14, 'abc'],
  322. {'abc': 'ABC'}, (), [], {}]
  323. l1 = copy(l)
  324. print l1==l
  325. l1 = map(copy, l)
  326. print l1==l
  327. l1 = deepcopy(l)
  328. print l1==l
  329. class C:
  330. def __init__(self, arg=None):
  331. self.a = 1
  332. self.arg = arg
  333. if __name__ == '__main__':
  334. import sys
  335. file = sys.argv[0]
  336. else:
  337. file = __file__
  338. self.fp = open(file)
  339. self.fp.close()
  340. def __getstate__(self):
  341. return {'a': self.a, 'arg': self.arg}
  342. def __setstate__(self, state):
  343. for key, value in state.iteritems():
  344. setattr(self, key, value)
  345. def __deepcopy__(self, memo=None):
  346. new = self.__class__(deepcopy(self.arg, memo))
  347. new.a = self.a
  348. return new
  349. c = C('argument sketch')
  350. l.append(c)
  351. l2 = copy(l)
  352. print l == l2
  353. print l
  354. print l2
  355. l2 = deepcopy(l)
  356. print l == l2
  357. print l
  358. print l2
  359. l.append({l[1]: l, 'xyz': l[2]})
  360. l3 = copy(l)
  361. import repr
  362. print map(repr.repr, l)
  363. print map(repr.repr, l1)
  364. print map(repr.repr, l2)
  365. print map(repr.repr, l3)
  366. l3 = deepcopy(l)
  367. import repr
  368. print map(repr.repr, l)
  369. print map(repr.repr, l1)
  370. print map(repr.repr, l2)
  371. print map(repr.repr, l3)
  372. if __name__ == '__main__':
  373. _test()