home *** CD-ROM | disk | FTP | other *** search
/ GameSpot.it / GameSpot Italia (2001).bin / demo / severancedemo / data1.cab / Program_Files / Lib / PythonLib / copy.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2000-10-13  |  10.1 KB  |  354 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. d[types.CodeType] = _copy_atomic
  89. d[types.TypeType] = _copy_atomic
  90. d[types.XRangeType] = _copy_atomic
  91. d[types.ClassType] = _copy_atomic
  92.  
  93. def _copy_list(x):
  94.     return x[:]
  95.  
  96. d[types.ListType] = _copy_list
  97.  
  98. def _copy_tuple(x):
  99.     return x[:]
  100.  
  101. d[types.TupleType] = _copy_tuple
  102.  
  103. def _copy_dict(x):
  104.     return x.copy()
  105.  
  106. d[types.DictionaryType] = _copy_dict
  107.  
  108. def _copy_inst(x):
  109.     if hasattr(x, '__copy__'):
  110.         return x.__copy__()
  111.     
  112.     if hasattr(x, '__getinitargs__'):
  113.         args = x.__getinitargs__()
  114.         y = apply(x.__class__, args)
  115.     else:
  116.         y = _EmptyClass()
  117.         y.__class__ = x.__class__
  118.     if hasattr(x, '__getstate__'):
  119.         state = x.__getstate__()
  120.     else:
  121.         state = x.__dict__
  122.     if hasattr(y, '__setstate__'):
  123.         y.__setstate__(state)
  124.     else:
  125.         y.__dict__.update(state)
  126.     return y
  127.  
  128. d[types.InstanceType] = _copy_inst
  129. del d
  130.  
  131. def deepcopy(x, memo = None):
  132.     """Deep copy operation on arbitrary Python objects.
  133.  
  134. \tSee the module's __doc__ string for more info.
  135. \t"""
  136.     if memo is None:
  137.         memo = { }
  138.     
  139.     d = id(x)
  140.     if memo.has_key(d):
  141.         return memo[d]
  142.     
  143.     
  144.     try:
  145.         copierfunction = _deepcopy_dispatch[type(x)]
  146.     except KeyError:
  147.         
  148.         try:
  149.             copier = x.__deepcopy__
  150.         except AttributeError:
  151.             raise error, 'un-deep-copyable object of type %s' % type(x)
  152.  
  153.         y = copier(memo)
  154.  
  155.     y = copierfunction(x, memo)
  156.     memo[d] = y
  157.     return y
  158.  
  159. _deepcopy_dispatch = d = { }
  160.  
  161. def _deepcopy_atomic(x, memo):
  162.     return x
  163.  
  164. d[types.NoneType] = _deepcopy_atomic
  165. d[types.IntType] = _deepcopy_atomic
  166. d[types.LongType] = _deepcopy_atomic
  167. d[types.FloatType] = _deepcopy_atomic
  168. d[types.StringType] = _deepcopy_atomic
  169. d[types.CodeType] = _deepcopy_atomic
  170. d[types.TypeType] = _deepcopy_atomic
  171. d[types.XRangeType] = _deepcopy_atomic
  172.  
  173. def _deepcopy_list(x, memo):
  174.     y = []
  175.     memo[id(x)] = y
  176.     for a in x:
  177.         y.append(deepcopy(a, memo))
  178.     
  179.     return y
  180.  
  181. d[types.ListType] = _deepcopy_list
  182.  
  183. def _deepcopy_tuple(x, memo):
  184.     y = []
  185.     for a in x:
  186.         y.append(deepcopy(a, memo))
  187.     
  188.     d = id(x)
  189.     
  190.     try:
  191.         return memo[d]
  192.     except KeyError:
  193.         0
  194.         0
  195.         x
  196.     except:
  197.         0
  198.  
  199.     for i in range(len(x)):
  200.         pass
  201.     else:
  202.         y = x
  203.     memo[d] = y
  204.     return y
  205.  
  206. d[types.TupleType] = _deepcopy_tuple
  207.  
  208. def _deepcopy_dict(x, memo):
  209.     y = { }
  210.     memo[id(x)] = y
  211.     for key in x.keys():
  212.         y[deepcopy(key, memo)] = deepcopy(x[key], memo)
  213.     
  214.     return y
  215.  
  216. d[types.DictionaryType] = _deepcopy_dict
  217.  
  218. def _keep_alive(x, memo):
  219.     '''Keeps a reference to the object x in the memo.
  220.  
  221. \tBecause we remember objects by their id, we have
  222. \tto assure that possibly temporary objects are kept
  223. \talive by referencing them.
  224. \tWe store a reference at the id of the memo, which should
  225. \tnormally not be used unless someone tries to deepcopy
  226. \tthe memo itself...
  227. \t'''
  228.     
  229.     try:
  230.         memo[id(memo)].append(x)
  231.     except KeyError:
  232.         memo[id(memo)] = [
  233.             x]
  234.  
  235.  
  236.  
  237. def _deepcopy_inst(x, memo):
  238.     if hasattr(x, '__deepcopy__'):
  239.         return x.__deepcopy__(memo)
  240.     
  241.     if hasattr(x, '__getinitargs__'):
  242.         args = x.__getinitargs__()
  243.         _keep_alive(args, memo)
  244.         args = deepcopy(args, memo)
  245.         y = apply(x.__class__, args)
  246.     else:
  247.         y = _EmptyClass()
  248.         y.__class__ = x.__class__
  249.     memo[id(x)] = y
  250.     if hasattr(x, '__getstate__'):
  251.         state = x.__getstate__()
  252.         _keep_alive(state, memo)
  253.     else:
  254.         state = x.__dict__
  255.     state = deepcopy(state, memo)
  256.     if hasattr(y, '__setstate__'):
  257.         y.__setstate__(state)
  258.     else:
  259.         y.__dict__.update(state)
  260.     return y
  261.  
  262. d[types.InstanceType] = _deepcopy_inst
  263. del d
  264. del types
  265.  
  266. class _EmptyClass:
  267.     pass
  268.  
  269.  
  270. def _test():
  271.     l = [
  272.         None,
  273.         1,
  274.         0x2L,
  275.         3.14,
  276.         'xyzzy',
  277.         (1, 0x2L),
  278.         [
  279.             3.14,
  280.             'abc'],
  281.         {
  282.             'abc': 'ABC' },
  283.         (),
  284.         [],
  285.         { }]
  286.     l1 = copy(l)
  287.     print l1 == l
  288.     l1 = map(copy, l)
  289.     print l1 == l
  290.     l1 = deepcopy(l)
  291.     print l1 == l
  292.     
  293.     class C:
  294.         
  295.         def __init__(self, arg = None):
  296.             self.a = 1
  297.             self.arg = arg
  298.             if __name__ == '__main__':
  299.                 import sys
  300.                 file = sys.argv[0]
  301.             else:
  302.                 file = __file__
  303.             self.fp = open(file)
  304.             self.fp.close()
  305.  
  306.         
  307.         def __getstate__(self):
  308.             return {
  309.                 'a': self.a,
  310.                 'arg': self.arg }
  311.  
  312.         
  313.         def __setstate__(self, state):
  314.             for key in state.keys():
  315.                 setattr(self, key, state[key])
  316.             
  317.  
  318.         
  319.         def __deepcopy__(self, memo = None):
  320.             new = self.__class__(deepcopy(self.arg, memo))
  321.             new.a = self.a
  322.             return new
  323.  
  324.  
  325.     c = C('argument sketch')
  326.     l.append(c)
  327.     l2 = copy(l)
  328.     print l == l2
  329.     print l
  330.     print l2
  331.     l2 = deepcopy(l)
  332.     print l == l2
  333.     print l
  334.     print l2
  335.     l.append({
  336.         l[1]: l,
  337.         'xyz': l[2] })
  338.     l3 = copy(l)
  339.     import repr
  340.     print map(repr.repr, l)
  341.     print map(repr.repr, l1)
  342.     print map(repr.repr, l2)
  343.     print map(repr.repr, l3)
  344.     l3 = deepcopy(l)
  345.     import repr
  346.     print map(repr.repr, l)
  347.     print map(repr.repr, l1)
  348.     print map(repr.repr, l2)
  349.     print map(repr.repr, l3)
  350.  
  351. if __name__ == '__main__':
  352.     _test()
  353.  
  354.