source: trunk/essentials/dev-lang/python/Lib/copy.py@ 3393

Last change on this file since 3393 was 3225, checked in by bird, 19 years ago

Python 2.5

File size: 10.7 KB
Line 
1"""Generic (shallow and deep) copying operations.
2
3Interface 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
10For module specific errors, copy.Error is raised.
11
12The difference between shallow and deep copying is only relevant for
13compound objects (objects that contain other objects, like lists or
14class instances).
15
16- A shallow copy constructs a new compound object and then (to the
17 extent possible) inserts *the same objects* into it 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
23Two problems often exist with deep copy operations that don't exist
24with 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
33Python'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
41This version does not copy types like module, class, function, method,
42nor stack trace, stack frame, nor file, socket, window, nor array, nor
43any similar types.
44
45Classes can use the same interfaces to control copying that they use
46to 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
51import types
52from copy_reg import dispatch_table
53
54class Error(Exception):
55 pass
56error = Error # backward compatibility
57
58try:
59 from org.python.core import PyStringMap
60except ImportError:
61 PyStringMap = None
62
63__all__ = ["Error", "copy", "deepcopy"]
64
65def copy(x):
66 """Shallow copy operation on arbitrary Python objects.
67
68 See the module's __doc__ string for more info.
69 """
70
71 cls = type(x)
72
73 copier = _copy_dispatch.get(cls)
74 if copier:
75 return copier(x)
76
77 copier = getattr(cls, "__copy__", None)
78 if copier:
79 return copier(x)
80
81 reductor = dispatch_table.get(cls)
82 if reductor:
83 rv = reductor(x)
84 else:
85 reductor = getattr(x, "__reduce_ex__", None)
86 if reductor:
87 rv = reductor(2)
88 else:
89 reductor = getattr(x, "__reduce__", None)
90 if reductor:
91 rv = reductor()
92 else:
93 raise Error("un(shallow)copyable object of type %s" % cls)
94
95 return _reconstruct(x, rv, 0)
96
97
98_copy_dispatch = d = {}
99
100def _copy_immutable(x):
101 return x
102for t in (type(None), int, long, float, bool, str, tuple,
103 frozenset, type, xrange, types.ClassType,
104 types.BuiltinFunctionType,
105 types.FunctionType):
106 d[t] = _copy_immutable
107for name in ("ComplexType", "UnicodeType", "CodeType"):
108 t = getattr(types, name, None)
109 if t is not None:
110 d[t] = _copy_immutable
111
112def _copy_with_constructor(x):
113 return type(x)(x)
114for t in (list, dict, set):
115 d[t] = _copy_with_constructor
116
117def _copy_with_copy_method(x):
118 return x.copy()
119if PyStringMap is not None:
120 d[PyStringMap] = _copy_with_copy_method
121
122def _copy_inst(x):
123 if hasattr(x, '__copy__'):
124 return x.__copy__()
125 if hasattr(x, '__getinitargs__'):
126 args = x.__getinitargs__()
127 y = x.__class__(*args)
128 else: