home *** CD-ROM | disk | FTP | other *** search
/ linuxmafia.com 2016 / linuxmafia.com.tar / linuxmafia.com / pub / palmos / pippy-0.6beta-src.tar.gz / pippy-0.6beta-src.tar / pippy-0.6beta-src / src / Lib / copy.py < prev    next >
Text File  |  2000-12-21  |  7KB  |  305 lines

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