PageRenderTime 57ms CodeModel.GetById 32ms RepoModel.GetById 1ms app.codeStats 0ms

/lib-python/2.7/copy.py

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