Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

copy.py 8.8KB

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 in 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. # XXX need to support copy_reg here too...
  36. import types
  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","error","copy","deepcopy"]
  45. def copy(x):
  46. """Shallow copy operation on arbitrary Python objects.
  47. See the module's __doc__ string for more info.
  48. """
  49. try:
  50. copierfunction = _copy_dispatch[type(x)]
  51. except KeyError:
  52. try:
  53. copier = x.__copy__
  54. except AttributeError:
  55. raise error, \
  56. "un(shallow)copyable object of type %s" % type(x)
  57. y = copier()
  58. else:
  59. y = copierfunction(x)
  60. return y
  61. _copy_dispatch = d = {}
  62. def _copy_atomic(x):
  63. return x
  64. d[types.NoneType] = _copy_atomic
  65. d[types.IntType] = _copy_atomic
  66. d[types.LongType] = _copy_atomic
  67. d[types.FloatType] = _copy_atomic
  68. d[types.StringType] = _copy_atomic
  69. d[types.UnicodeType] = _copy_atomic
  70. try:
  71. d[types.CodeType] = _copy_atomic
  72. except AttributeError:
  73. pass
  74. d[types.TypeType] = _copy_atomic
  75. d[types.XRangeType] = _copy_atomic
  76. d[types.ClassType] = _copy_atomic
  77. def _copy_list(x):
  78. return x[:]
  79. d[types.ListType] = _copy_list
  80. def _copy_tuple(x):
  81. return x[:]
  82. d[types.TupleType] = _copy_tuple
  83. def _copy_dict(x):
  84. return x.copy()
  85. d[types.DictionaryType] = _copy_dict
  86. if PyStringMap is not None:
  87. d[PyStringMap] = _copy_dict
  88. def _copy_inst(x):
  89. if hasattr(x, '__copy__'):
  90. return x.__copy__()
  91. if hasattr(x, '__getinitargs__'):
  92. args = x.__getinitargs__()
  93. y = apply(x.__class__, args)
  94. else:
  95. if hasattr(x.__class__, '__del__'):
  96. y = _EmptyClassDel()
  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):
  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. if memo.has_key(d):
  119. return memo[d]
  120. try:
  121. copierfunction = _deepcopy_dispatch[type(x)]
  122. except KeyError:
  123. try:
  124. copier = x.__deepcopy__
  125. except AttributeError:
  126. raise error, \
  127. "un-deep-copyable object of type %s" % type(x)
  128. y = copier(memo)
  129. else:
  130. y = copierfunction(x, memo)
  131. memo[d] = y
  132. return y
  133. _deepcopy_dispatch = d = {}
  134. def _deepcopy_atomic(x, memo):
  135. return x
  136. d[types.NoneType] = _deepcopy_atomic
  137. d[types.IntType] = _deepcopy_atomic
  138. d[types.LongType] = _deepcopy_atomic
  139. d[types.FloatType] = _deepcopy_atomic
  140. d[types.StringType] = _deepcopy_atomic
  141. d[types.UnicodeType] = _deepcopy_atomic
  142. d[types.CodeType] = _deepcopy_atomic
  143. d[types.TypeType] = _deepcopy_atomic
  144. d[types.XRangeType] = _deepcopy_atomic
  145. def _deepcopy_list(x, memo):
  146. y = []
  147. memo[id(x)] = y
  148. for a in x:
  149. y.append(deepcopy(a, memo))
  150. return y
  151. d[types.ListType] = _deepcopy_list
  152. def _deepcopy_tuple(x, memo):
  153. y = []
  154. for a in x:
  155. y.append(deepcopy(a, memo))
  156. d = id(x)
  157. try:
  158. return memo[d]
  159. except KeyError:
  160. pass
  161. for i in range(len(x)):
  162. if x[i] is not y[i]:
  163. y = tuple(y)
  164. break
  165. else:
  166. y = x
  167. memo[d] = y
  168. return y
  169. d[types.TupleType] = _deepcopy_tuple
  170. def _deepcopy_dict(x, memo):
  171. y = {}
  172. memo[id(x)] = y
  173. for key in x.keys():
  174. y[deepcopy(key, memo)] = deepcopy(x[key], memo)
  175. return y
  176. d[types.DictionaryType] = _deepcopy_dict
  177. if PyStringMap is not None:
  178. d[PyStringMap] = _deepcopy_dict
  179. def _keep_alive(x, memo):
  180. """Keeps a reference to the object x in the memo.
  181. Because we remember objects by their id, we have
  182. to assure that possibly temporary objects are kept
  183. alive by referencing them.
  184. We store a reference at the id of the memo, which should
  185. normally not be used unless someone tries to deepcopy
  186. the memo itself...
  187. """
  188. try:
  189. memo[id(memo)].append(x)
  190. except KeyError:
  191. # aha, this is the first one :-)
  192. memo[id(memo)]=[x]
  193. def _deepcopy_inst(x, memo):
  194. if hasattr(x, '__deepcopy__'):
  195. return x.__deepcopy__(memo)
  196. if hasattr(x, '__getinitargs__'):
  197. args = x.__getinitargs__()
  198. _keep_alive(args, memo)
  199. args = deepcopy(args, memo)
  200. y = apply(x.__class__, args)
  201. else:
  202. if hasattr(x.__class__, '__del__'):
  203. y = _EmptyClassDel()
  204. else:
  205. y = _EmptyClass()
  206. y.__class__ = x.__class__
  207. memo[id(x)] = y
  208. if hasattr(x, '__getstate__'):
  209. state = x.__getstate__()
  210. _keep_alive(state, memo)
  211. else:
  212. state = x.__dict__
  213. state = deepcopy(state, memo)
  214. if hasattr(y, '__setstate__'):
  215. y.__setstate__(state)
  216. else:
  217. y.__dict__.update(state)
  218. return y
  219. d[types.InstanceType] = _deepcopy_inst
  220. del d
  221. del types
  222. # Helper for instance creation without calling __init__
  223. class _EmptyClass:
  224. pass
  225. # Helper for instance creation without calling __init__. Used when
  226. # the source class contains a __del__ attribute.
  227. class _EmptyClassDel:
  228. def __del__(self):
  229. pass
  230. def _test():
  231. l = [None, 1, 2L, 3.14, 'xyzzy', (1, 2L), [3.14, 'abc'],
  232. {'abc': 'ABC'}, (), [], {}]
  233. l1 = copy(l)
  234. print l1==l
  235. l1 = map(copy, l)
  236. print l1==l
  237. l1 = deepcopy(l)
  238. print l1==l
  239. class C:
  240. def __init__(self, arg=None):
  241. self.a = 1
  242. self.arg = arg
  243. if __name__ == '__main__':
  244. import sys
  245. file = sys.argv[0]
  246. else:
  247. file = __file__
  248. self.fp = open(file)
  249. self.fp.close()
  250. def __getstate__(self):
  251. return {'a': self.a, 'arg': self.arg}
  252. def __setstate__(self, state):
  253. for key in state.keys():
  254. setattr(self, key, state[key])
  255. def __deepcopy__(self, memo = None):
  256. new = self.__class__(deepcopy(self.arg, memo))
  257. new.a = self.a
  258. return new
  259. c = C('argument sketch')
  260. l.append(c)
  261. l2 = copy(l)
  262. print l == l2
  263. print l
  264. print l2
  265. l2 = deepcopy(l)
  266. print l == l2
  267. print l
  268. print l2
  269. l.append({l[1]: l, 'xyz': l[2]})
  270. l3 = copy(l)
  271. import repr
  272. print map(repr.repr, l)
  273. print map(repr.repr, l1)
  274. print map(repr.repr, l2)
  275. print map(repr.repr, l3)
  276. l3 = deepcopy(l)
  277. import repr
  278. print map(repr.repr, l)
  279. print map(repr.repr, l1)
  280. print map(repr.repr, l2)
  281. print map(repr.repr, l3)
  282. if __name__ == '__main__':
  283. _test()