home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / pytho152.zip / emx / lib / python1.5 / copy.py < prev    next >
Text File  |  2000-08-10  |  7KB  |  307 lines

  1. """\
  2. Generic (shallow and deep) copying operations
  3. =============================================
  4.  
  5. Interface summary:
  6.  
  7.     import copy
  8.  
  9.     x = copy.copy(y)    # make a shallow copy of y
  10.     x = copy.deepcopy(y)    # make a deep copy of y
  11.  
  12. For module specific errors, copy.error is raised.
  13.  
  14. The difference between shallow and deep copying is only relevant for
  15. compound objects (objects that contain other objects, like lists or
  16. class instances).
  17.  
  18. - A shallow copy constructs a new compound object and then (to the
  19.   extent possible) inserts *the same objects* into in that the
  20.   original contains.
  21.  
  22. - A deep copy constructs a new compound object and then, recursively,
  23.   inserts *copies* into it of the objects found in the original.
  24.  
  25. Two problems often exist with deep copy operations that don't exist
  26. with shallow copy operations:
  27.  
  28.  a) recursive objects (compound objects that, directly or indirectly,
  29.     contain a reference to themselves) may cause a recursive loop
  30.  
  31.  b) because deep copy copies *everything* it may copy too much, e.g.
  32.     administrative data structures that should be shared even between
  33.     copies
  34.  
  35. Python's deep copy operation avoids these problems by:
  36.  
  37.  a) keeping a table of objects already copied during the current
  38.     copying pass
  39.  
  40.  b) letting user-defined classes override the copying operation or the
  41.     set of components copied
  42.  
  43. This version does not copy types like module, class, function, method,
  44. nor stack trace, stack frame, nor file, socket, window, nor array, nor
  45. any similar types.
  46.  
  47. Classes can use the same interfaces to control copying that they use
  48. to control pickling: they can define methods called __getinitargs__(),
  49. __getstate__() and __setstate__().  See the documentation for module
  50. "pickle" for information on these methods.
  51. """
  52.  
  53. # XXX need to support copy_reg here too...
  54.  
  55. import types
  56.  
  57. error = 'copy.error'
  58. Error = error # backward compatibility
  59.  
  60. def copy(x):
  61.     """Shallow copy operation on arbitrary Python objects.
  62.  
  63.     See the module's __doc__ string for more info.
  64.     """
  65.  
  66.     try:
  67.         copierfunction = _copy_dispatch[type(x)]
  68.     except KeyError:
  69.         try:
  70.             copier = x.__copy__
  71.         except AttributeError:
  72.             raise error, \
  73.                   "un(shallow)copyable object of type %s" % type(x)
  74.         y = copier()
  75.     else:
  76.         y = copierfunction(x)
  77.     return y
  78.  
  79. _copy_dispatch = d = {}
  80.  
  81. def _copy_atomic(x):
  82.     return x
  83. d[types.NoneType] = _copy_atomic
  84. d[types.IntType] = _copy_atomic
  85. d[types.LongType] = _copy_atomic
  86. d[types.FloatType] = _copy_atomic
  87. d[types.StringType] = _copy_atomic
  88. try:
  89.     d[types.CodeType] = _copy_atomic
  90. except AttributeError:
  91.     pass
  92. d[types.TypeType] = _copy_atomic
  93. d[types.XRangeType] = _copy_atomic
  94. d[types.ClassType] = _copy_atomic
  95.  
  96. def _copy_list(x):
  97.     return x[:]
  98. d[types.ListType] = _copy_list
  99.  
  100. def _copy_tuple(x):
  101.     return x[:]
  102. d[types.TupleType] = _copy_tuple
  103.  
  104. def _copy_dict(x):
  105.     return x.copy()
  106. d[types.DictionaryType] = _copy_dict
  107.  
  108. def _copy_inst(x):
  109.     if hasattr(x, '__copy__'):
  110.         return x.__copy__()
  111.     if hasattr(x, '__getinitargs__'):
  112.         args = x.__getinitargs__()
  113.         y = apply(x.__class__, args)
  114.     else:
  115.         y = _EmptyClass()
  116.         y.__class__ = x.__class__
  117.     if hasattr(x, '__getstate__'):
  118.         state = x.__getstate__()
  119.     else:
  120.         state = x.__dict__
  121.     if hasattr(y, '__setstate__'):
  122.         y.__setstate__(state)
  123.     else:
  124.         y.__dict__.update(state)
  125.     return y
  126. d[types.InstanceType] = _copy_inst
  127.  
  128. del d
  129.  
  130. def deepcopy(x, memo = None):
  131.     """Deep copy operation on arbitrary Python objects.
  132.  
  133.     See the module's __doc__ string for more info.
  134.     """
  135.  
  136.     if memo is None:
  137.         memo = {}
  138.     d = id(x)
  139.     if memo.has_key(d):
  140.         return memo[d]
  141.     try:
  142.         copierfunction = _deepcopy_dispatch[type(x)]
  143.     except KeyError:
  144.         try:
  145.             copier = x.__deepcopy__
  146.         except AttributeError:
  147.             raise error, \
  148.                   "un-deep-copyable object of type %s" % type(x)
  149.         y = copier(memo)
  150.     else:
  151.         y = copierfunction(x, memo)
  152.     memo[d] = y
  153.     return y
  154.  
  155. _deepcopy_dispatch = d = {}
  156.  
  157. def _deepcopy_atomic(x, memo):
  158.     return x
  159. d[types.NoneType] = _deepcopy_atomic
  160. d[types.IntType] = _deepcopy_atomic
  161. d[types.LongType] = _deepcopy_atomic
  162. d[types.FloatType] = _deepcopy_atomic
  163. d[types.StringType] = _deepcopy_atomic
  164. d[types.CodeType] = _deepcopy_atomic
  165. d[types.TypeType] = _deepcopy_atomic
  166. d[types.XRangeType] = _deepcopy_atomic
  167.  
  168. def _deepcopy_list(x, memo):
  169.     y = []
  170.     memo[id(x)] = y
  171.     for a in x:
  172.         y.append(deepcopy(a, memo))
  173.     return y
  174. d[types.ListType] = _deepcopy_list
  175.  
  176. def _deepcopy_tuple(x, memo):
  177.     y = []
  178.     for a in x:
  179.         y.append(deepcopy(a, memo))
  180.     d = id(x)
  181.     try:
  182.         return memo[d]
  183.     except KeyError:
  184.         pass
  185.     for i in range(len(x)):
  186.         if x[i] is not y[i]:
  187.             y = tuple(y)
  188.             break
  189.     else:
  190.         y = x
  191.     memo[d] = y
  192.     return y
  193. d[types.TupleType] = _deepcopy_tuple
  194.  
  195. def _deepcopy_dict(x, memo):
  196.     y = {}
  197.     memo[id(x)] = y
  198.     for key in x.keys():
  199.         y[deepcopy(key, memo)] = deepcopy(x[key], memo)
  200.     return y
  201. d[types.DictionaryType] = _deepcopy_dict
  202.  
  203. def _keep_alive(x, memo):
  204.     """Keeps a reference to the object x in the memo.
  205.  
  206.     Because we remember objects by their id, we have
  207.     to assure that possibly temporary objects are kept
  208.     alive by referencing them.
  209.     We store a reference at the id of the memo, which should
  210.     normally not be used unless someone tries to deepcopy
  211.     the memo itself...
  212.     """
  213.     try:
  214.         memo[id(memo)].append(x)
  215.     except KeyError:
  216.         # aha, this is the first one :-)
  217.         memo[id(memo)]=[x]
  218.  
  219. def _deepcopy_inst(x, memo):
  220.     if hasattr(x, '__deepcopy__'):
  221.         return x.__deepcopy__(memo)
  222.     if hasattr(x, '__getinitargs__'):
  223.         args = x.__getinitargs__()
  224.         _keep_alive(args, memo)
  225.         args = deepcopy(args, memo)
  226.         y = apply(x.__class__, args)
  227.     else:
  228.         y = _EmptyClass()
  229.         y.__class__ = x.__class__
  230.     memo[id(x)] = y
  231.     if hasattr(x, '__getstate__'):
  232.         state = x.__getstate__()
  233.         _keep_alive(state, memo)
  234.     else:
  235.         state = x.__dict__
  236.     state = deepcopy(state, memo)
  237.     if hasattr(y, '__setstate__'):
  238.         y.__setstate__(state)
  239.     else:
  240.         y.__dict__.update(state)
  241.     return y
  242. d[types.InstanceType] = _deepcopy_inst
  243.  
  244. del d
  245.  
  246. del types
  247.  
  248. # Helper for instance creation without calling __init__
  249. class _EmptyClass:
  250.     pass
  251.  
  252. def _test():
  253.     l = [None, 1, 2L, 3.14, 'xyzzy', (1, 2L), [3.14, 'abc'],
  254.          {'abc': 'ABC'}, (), [], {}]
  255.     l1 = copy(l)
  256.     print l1==l
  257.     l1 = map(copy, l)
  258.     print l1==l
  259.     l1 = deepcopy(l)
  260.     print l1==l
  261.     class C:
  262.         def __init__(self, arg=None):
  263.             self.a = 1
  264.             self.arg = arg
  265.             if __name__ == '__main__':
  266.                 import sys
  267.                 file = sys.argv[0]
  268.             else:
  269.                 file = __file__
  270.             self.fp = open(file)
  271.             self.fp.close()
  272.         def __getstate__(self):
  273.             return {'a': self.a, 'arg': self.arg}
  274.         def __setstate__(self, state):
  275.             for key in state.keys():
  276.                 setattr(self, key, state[key])
  277.         def __deepcopy__(self, memo = None):
  278.             new = self.__class__(deepcopy(self.arg, memo))
  279.             new.a = self.a
  280.             return new
  281.     c = C('argument sketch')
  282.     l.append(c)
  283.     l2 = copy(l)
  284.     print l == l2
  285.     print l
  286.     print l2
  287.     l2 = deepcopy(l)
  288.     print l == l2
  289.     print l
  290.     print l2
  291.     l.append({l[1]: l, 'xyz': l[2]})
  292.     l3 = copy(l)
  293.     import repr
  294.     print map(repr.repr, l)
  295.     print map(repr.repr, l1)
  296.     print map(repr.repr, l2)
  297.     print map(repr.repr, l3)
  298.     l3 = deepcopy(l)
  299.     import repr
  300.     print map(repr.repr, l)
  301.     print map(repr.repr, l1)
  302.     print map(repr.repr, l2)
  303.     print map(repr.repr, l3)
  304.  
  305. if __name__ == '__main__':
  306.     _test()
  307.