home *** CD-ROM | disk | FTP | other *** search
/ PC Extra 07 & 08 / pca1507.iso / Software / psp8 / Data1.cab / copy.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2003-04-22  |  12.4 KB  |  440 lines

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