home *** CD-ROM | disk | FTP | other *** search
/ MacHack 2000 / MacHack 2000.toast / pc / The Hacks / MacHacksBug / Python 1.5.2c1 / Lib / copy.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2000-06-23  |  10.6 KB  |  359 lines

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