You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

388 lines
10 KiB

Merged revisions 61834,61841-61842,61851-61853,61863-61864,61869-61870,61874,61889 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r61834 | raymond.hettinger | 2008-03-24 07:07:49 +0100 (Mon, 24 Mar 2008) | 1 line Tighten documentation for Random.triangular. ........ r61841 | raymond.hettinger | 2008-03-24 09:17:39 +0100 (Mon, 24 Mar 2008) | 1 line Issue 2460: Make Ellipsis objects copyable. ........ r61842 | georg.brandl | 2008-03-24 10:34:34 +0100 (Mon, 24 Mar 2008) | 2 lines #1700821: add a note to audioop docs about signedness of sample formats. ........ r61851 | christian.heimes | 2008-03-24 20:57:42 +0100 (Mon, 24 Mar 2008) | 1 line Added quick hack for bzr ........ r61852 | christian.heimes | 2008-03-24 20:58:17 +0100 (Mon, 24 Mar 2008) | 1 line Added quick hack for bzr ........ r61853 | amaury.forgeotdarc | 2008-03-24 22:04:10 +0100 (Mon, 24 Mar 2008) | 4 lines Issue2469: Correct a typo I introduced at r61793: compilation error with UCS4 builds. All buildbots compile with UCS2... ........ r61863 | neal.norwitz | 2008-03-25 05:17:38 +0100 (Tue, 25 Mar 2008) | 2 lines Fix a bunch of UnboundLocalErrors when the tests fail. ........ r61864 | neal.norwitz | 2008-03-25 05:18:18 +0100 (Tue, 25 Mar 2008) | 2 lines Try to fix a bunch of compiler warnings on Win64. ........ r61869 | neal.norwitz | 2008-03-25 07:35:10 +0100 (Tue, 25 Mar 2008) | 3 lines Don't try to close a non-open file. Don't let file removal cause the test to fail. ........ r61870 | neal.norwitz | 2008-03-25 08:00:39 +0100 (Tue, 25 Mar 2008) | 7 lines Try to get this test to be more stable: * disable gc during the test run because we are spawning objects and there was an exception when calling Popen.__del__ * Always set an alarm handler so the process doesn't exit if the test fails (should probably add assertions on the value of hndl_called in more places) * Using a negative time causes Linux to treat it as zero, so disable that test. ........ r61874 | gregory.p.smith | 2008-03-25 08:31:28 +0100 (Tue, 25 Mar 2008) | 2 lines Use a 32-bit unsigned int here, a long is not needed. ........ r61889 | georg.brandl | 2008-03-25 12:59:51 +0100 (Tue, 25 Mar 2008) | 2 lines Move declarations to block start. ........
18 years ago
Merged revisions 61834,61841-61842,61851-61853,61863-61864,61869-61870,61874,61889 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r61834 | raymond.hettinger | 2008-03-24 07:07:49 +0100 (Mon, 24 Mar 2008) | 1 line Tighten documentation for Random.triangular. ........ r61841 | raymond.hettinger | 2008-03-24 09:17:39 +0100 (Mon, 24 Mar 2008) | 1 line Issue 2460: Make Ellipsis objects copyable. ........ r61842 | georg.brandl | 2008-03-24 10:34:34 +0100 (Mon, 24 Mar 2008) | 2 lines #1700821: add a note to audioop docs about signedness of sample formats. ........ r61851 | christian.heimes | 2008-03-24 20:57:42 +0100 (Mon, 24 Mar 2008) | 1 line Added quick hack for bzr ........ r61852 | christian.heimes | 2008-03-24 20:58:17 +0100 (Mon, 24 Mar 2008) | 1 line Added quick hack for bzr ........ r61853 | amaury.forgeotdarc | 2008-03-24 22:04:10 +0100 (Mon, 24 Mar 2008) | 4 lines Issue2469: Correct a typo I introduced at r61793: compilation error with UCS4 builds. All buildbots compile with UCS2... ........ r61863 | neal.norwitz | 2008-03-25 05:17:38 +0100 (Tue, 25 Mar 2008) | 2 lines Fix a bunch of UnboundLocalErrors when the tests fail. ........ r61864 | neal.norwitz | 2008-03-25 05:18:18 +0100 (Tue, 25 Mar 2008) | 2 lines Try to fix a bunch of compiler warnings on Win64. ........ r61869 | neal.norwitz | 2008-03-25 07:35:10 +0100 (Tue, 25 Mar 2008) | 3 lines Don't try to close a non-open file. Don't let file removal cause the test to fail. ........ r61870 | neal.norwitz | 2008-03-25 08:00:39 +0100 (Tue, 25 Mar 2008) | 7 lines Try to get this test to be more stable: * disable gc during the test run because we are spawning objects and there was an exception when calling Popen.__del__ * Always set an alarm handler so the process doesn't exit if the test fails (should probably add assertions on the value of hndl_called in more places) * Using a negative time causes Linux to treat it as zero, so disable that test. ........ r61874 | gregory.p.smith | 2008-03-25 08:31:28 +0100 (Tue, 25 Mar 2008) | 2 lines Use a 32-bit unsigned int here, a long is not needed. ........ r61889 | georg.brandl | 2008-03-25 12:59:51 +0100 (Tue, 25 Mar 2008) | 2 lines Move declarations to block start. ........
18 years ago
Merged revisions 55007-55179 via svnmerge from svn+ssh://pythondev@svn.python.org/python/branches/p3yk ........ r55077 | guido.van.rossum | 2007-05-02 11:54:37 -0700 (Wed, 02 May 2007) | 2 lines Use the new print syntax, at least. ........ r55142 | fred.drake | 2007-05-04 21:27:30 -0700 (Fri, 04 May 2007) | 1 line remove old cruftiness ........ r55143 | fred.drake | 2007-05-04 21:52:16 -0700 (Fri, 04 May 2007) | 1 line make this work with the new Python ........ r55162 | neal.norwitz | 2007-05-06 22:29:18 -0700 (Sun, 06 May 2007) | 1 line Get asdl code gen working with Python 2.3. Should continue to work with 3.0 ........ r55164 | neal.norwitz | 2007-05-07 00:00:38 -0700 (Mon, 07 May 2007) | 1 line Verify checkins to p3yk (sic) branch go to 3000 list. ........ r55166 | neal.norwitz | 2007-05-07 00:12:35 -0700 (Mon, 07 May 2007) | 1 line Fix this test so it runs again by importing warnings_test properly. ........ r55167 | neal.norwitz | 2007-05-07 01:03:22 -0700 (Mon, 07 May 2007) | 8 lines So long xrange. range() now supports values that are outside -sys.maxint to sys.maxint. floats raise a TypeError. This has been sitting for a long time. It probably has some problems and needs cleanup. Objects/rangeobject.c now uses 4-space indents since it is almost completely new. ........ r55171 | guido.van.rossum | 2007-05-07 10:21:26 -0700 (Mon, 07 May 2007) | 4 lines Fix two tests that were previously depending on significant spaces at the end of a line (and before that on Python 2.x print behavior that has no exact equivalent in 3.0). ........
19 years ago
  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. copier = getattr(cls, "__copy__", None)
  56. if copier:
  57. return copier(x)
  58. reductor = dispatch_table.get(cls)
  59. if reductor:
  60. rv = reductor(x)
  61. else:
  62. reductor = getattr(x, "__reduce_ex__", None)
  63. if reductor:
  64. rv = reductor(2)
  65. else:
  66. reductor = getattr(x, "__reduce__", None)
  67. if reductor:
  68. rv = reductor()
  69. else:
  70. raise Error("un(shallow)copyable object of type %s" % cls)
  71. return _reconstruct(x, rv, 0)
  72. _copy_dispatch = d = {}
  73. def _copy_immutable(x):
  74. return x
  75. for t in (type(None), int, float, bool, str, tuple,
  76. frozenset, type, range,
  77. types.BuiltinFunctionType, type(Ellipsis),
  78. types.FunctionType, weakref.ref):
  79. d[t] = _copy_immutable
  80. t = getattr(types, "CodeType", None)
  81. if t is not None:
  82. d[t] = _copy_immutable
  83. for name in ("complex", "unicode"):
  84. t = getattr(builtins, name, None)
  85. if t is not None:
  86. d[t] = _copy_immutable
  87. def _copy_with_constructor(x):
  88. return type(x)(x)
  89. for t in (list, dict, set):
  90. d[t] = _copy_with_constructor
  91. def _copy_with_copy_method(x):
  92. return x.copy()
  93. if PyStringMap is not None:
  94. d[PyStringMap] = _copy_with_copy_method
  95. del d
  96. def deepcopy(x, memo=None, _nil=[]):
  97. """Deep copy operation on arbitrary Python objects.
  98. See the module's __doc__ string for more info.
  99. """
  100. if memo is None:
  101. memo = {}
  102. d = id(x)
  103. y = memo.get(d, _nil)
  104. if y is not _nil:
  105. return y
  106. cls = type(x)
  107. copier = _deepcopy_dispatch.get(cls)
  108. if copier:
  109. y = copier(x, memo)
  110. else:
  111. try:
  112. issc = issubclass(cls, type)
  113. except TypeError: # cls is not a class (old Boost; see SF #502085)
  114. issc = 0
  115. if issc:
  116. y = _deepcopy_atomic(x, memo)
  117. else:
  118. copier = getattr(x, "__deepcopy__", None)
  119. if copier:
  120. y = copier(memo)
  121. else:
  122. reductor = dispatch_table.get(cls)
  123. if reductor:
  124. rv = reductor(x)
  125. else:
  126. reductor = getattr(x, "__reduce_ex__", None)
  127. if reductor:
  128. rv = reductor(2)
  129. else:
  130. reductor = getattr(x, "__reduce__", None)
  131. if reductor:
  132. rv = reductor()
  133. else:
  134. raise Error(
  135. "un(deep)copyable object of type %s" % cls)
  136. y = _reconstruct(x, rv, 1, memo)
  137. memo[d] = y
  138. _keep_alive(x, memo) # Make sure x lives at least as long as d
  139. return y
  140. _deepcopy_dispatch = d = {}
  141. def _deepcopy_atomic(x, memo):
  142. return x
  143. d[type(None)] = _deepcopy_atomic
  144. d[type(Ellipsis)] = _deepcopy_atomic
  145. d[int] = _deepcopy_atomic
  146. d[float] = _deepcopy_atomic
  147. d[bool] = _deepcopy_atomic
  148. try:
  149. d[complex] = _deepcopy_atomic
  150. except NameError:
  151. pass
  152. d[bytes] = _deepcopy_atomic
  153. d[str] = _deepcopy_atomic
  154. try:
  155. d[types.CodeType] = _deepcopy_atomic
  156. except AttributeError:
  157. pass
  158. d[type] = _deepcopy_atomic
  159. d[range] = _deepcopy_atomic
  160. d[types.BuiltinFunctionType] = _deepcopy_atomic
  161. d[types.FunctionType] = _deepcopy_atomic
  162. d[weakref.ref] = _deepcopy_atomic
  163. def _deepcopy_list(x, memo):
  164. y = []
  165. memo[id(x)] = y
  166. for a in x:
  167. y.append(deepcopy(a, memo))
  168. return y
  169. d[list] = _deepcopy_list
  170. def _deepcopy_tuple(x, memo):
  171. y = []
  172. for a in x:
  173. y.append(deepcopy(a, memo))
  174. d = id(x)
  175. try:
  176. return memo[d]
  177. except KeyError:
  178. pass
  179. for i in range(len(x)):
  180. if x[i] is not y[i]:
  181. y = tuple(y)
  182. break
  183. else:
  184. y = x
  185. memo[d] = y
  186. return y
  187. d[tuple] = _deepcopy_tuple
  188. def _deepcopy_dict(x, memo):
  189. y = {}
  190. memo[id(x)] = y
  191. for key, value in x.items():
  192. y[deepcopy(key, memo)] = deepcopy(value, memo)
  193. return y
  194. d[dict] = _deepcopy_dict
  195. if PyStringMap is not None:
  196. d[PyStringMap] = _deepcopy_dict
  197. def _deepcopy_method(x, memo): # Copy instance methods
  198. return type(x)(x.__func__, deepcopy(x.__self__, memo))
  199. _deepcopy_dispatch[types.MethodType] = _deepcopy_method
  200. def _keep_alive(x, memo):
  201. """Keeps a reference to the object x in the memo.
  202. Because we remember objects by their id, we have
  203. to assure that possibly temporary objects are kept
  204. alive by referencing them.
  205. We store a reference at the id of the memo, which should
  206. normally not be used unless someone tries to deepcopy
  207. the memo itself...
  208. """
  209. try:
  210. memo[id(memo)].append(x)
  211. except KeyError:
  212. # aha, this is the first one :-)
  213. memo[id(memo)]=[x]
  214. def _reconstruct(x, info, deep, memo=None):
  215. if isinstance(info, str):
  216. return x
  217. assert isinstance(info, tuple)
  218. if memo is None:
  219. memo = {}
  220. n = len(info)
  221. assert n in (2, 3, 4, 5)
  222. callable, args = info[:2]
  223. if n > 2:
  224. state = info[2]
  225. else:
  226. state = {}
  227. if n > 3:
  228. listiter = info[3]
  229. else:
  230. listiter = None
  231. if n > 4:
  232. dictiter = info[4]
  233. else:
  234. dictiter = None
  235. if deep:
  236. args = deepcopy(args, memo)
  237. y = callable(*args)
  238. memo[id(x)] = y
  239. if state:
  240. if deep:
  241. state = deepcopy(state, memo)
  242. if hasattr(y, '__setstate__'):
  243. y.__setstate__(state)
  244. else:
  245. if isinstance(state, tuple) and len(state) == 2:
  246. state, slotstate = state
  247. else:
  248. slotstate = None
  249. if state is not None:
  250. y.__dict__.update(state)
  251. if slotstate is not None:
  252. for key, value in slotstate.items():
  253. setattr(y, key, value)
  254. if listiter is not None:
  255. for item in listiter:
  256. if deep:
  257. item = deepcopy(item, memo)
  258. y.append(item)
  259. if dictiter is not None:
  260. for key, value in dictiter:
  261. if deep:
  262. key = deepcopy(key, memo)
  263. value = deepcopy(value, memo)
  264. y[key] = value
  265. return y
  266. del d
  267. del types
  268. # Helper for instance creation without calling __init__
  269. class _EmptyClass:
  270. pass
  271. def _test():
  272. l = [None, 1, 2, 3.14, 'xyzzy', (1, 2), [3.14, 'abc'],
  273. {'abc': 'ABC'}, (), [], {}]
  274. l1 = copy(l)
  275. print(l1==l)
  276. l1 = map(copy, l)
  277. print(l1==l)
  278. l1 = deepcopy(l)
  279. print(l1==l)
  280. class C:
  281. def __init__(self, arg=None):
  282. self.a = 1
  283. self.arg = arg
  284. if __name__ == '__main__':
  285. import sys
  286. file = sys.argv[0]
  287. else:
  288. file = __file__
  289. self.fp = open(file)
  290. self.fp.close()
  291. def __getstate__(self):
  292. return {'a': self.a, 'arg': self.arg}
  293. def __setstate__(self, state):
  294. for key, value in state.items():
  295. setattr(self, key, value)
  296. def __deepcopy__(self, memo=None):
  297. new = self.__class__(deepcopy(self.arg, memo))
  298. new.a = self.a
  299. return new
  300. c = C('argument sketch')
  301. l.append(c)
  302. l2 = copy(l)
  303. print(l == l2)
  304. print(l)
  305. print(l2)
  306. l2 = deepcopy(l)
  307. print(l == l2)
  308. print(l)
  309. print(l2)
  310. l.append({l[1]: l, 'xyz': l[2]})
  311. l3 = copy(l)
  312. import reprlib
  313. print(map(reprlib.repr, l))
  314. print(map(reprlib.repr, l1))
  315. print(map(reprlib.repr, l2))
  316. print(map(reprlib.repr, l3))
  317. l3 = deepcopy(l)
  318. print(map(reprlib.repr, l))
  319. print(map(reprlib.repr, l1))
  320. print(map(reprlib.repr, l2))
  321. print(map(reprlib.repr, l3))
  322. class odict(dict):
  323. def __init__(self, d = {}):
  324. self.a = 99
  325. dict.__init__(self, d)
  326. def __setitem__(self, k, i):
  327. dict.__setitem__(self, k, i)
  328. self.a
  329. o = odict({"A" : "B"})
  330. x = deepcopy(o)
  331. print(o, x)
  332. if __name__ == '__main__':
  333. _test()