1 \section{\module{copy
} ---
2 Shallow and deep copy operations.
}
3 \declaremodule{standard
}{copy
}
5 \modulesynopsis{Shallow and deep copy operations.
}
7 \setindexsubitem{(copy function)
}
11 This module provides generic (shallow and deep) copying operations.
18 x = copy.copy(y) # make a shallow copy of y
19 x = copy.deepcopy(y) # make a deep copy of y
22 For module specific errors,
\code{copy.error
} is raised.
24 The difference between shallow and deep copying is only relevant for
25 compound objects (objects that contain other objects, like lists or
31 A
\emph{shallow copy
} constructs a new compound object and then (to the
32 extent possible) inserts
\emph{references
} into it to the objects found
36 A
\emph{deep copy
} constructs a new compound object and then,
37 recursively, inserts
\emph{copies
} into it of the objects found in the
42 Two problems often exist with deep copy operations that don't exist
43 with shallow copy operations:
48 Recursive objects (compound objects that, directly or indirectly,
49 contain a reference to themselves) may cause a recursive loop.
52 Because deep copy copies
\emph{everything
} it may copy too much, e.g.\
53 administrative data structures that should be shared even between
58 Python's
\code{deepcopy()
} operation avoids these problems by:
63 keeping a ``memo'' dictionary of objects already copied during the current
67 letting user-defined classes override the copying operation or the
68 set of components copied.
72 This version does not copy types like module, class, function, method,
73 nor stack trace, stack frame, nor file, socket, window, nor array, nor
76 Classes can use the same interfaces to control copying that they use
77 to control pickling: they can define methods called
78 \code{__getinitargs__()
},
\code{__getstate__()
} and
79 \code{__setstate__()
}. See the description of module
\code{pickle
}
80 for information on these methods.
81 The copy module does not use the
\module{copy_reg
} registration
83 \refstmodindex{pickle
}
84 \setindexsubitem{(copy protocol)
}
85 \ttindex{__getinitargs__
}
86 \ttindex{__getstate__
}
87 \ttindex{__setstate__
}
89 In order for a class to define its own copy implementation, it can
90 define special methods
\method{__copy__()
}\ttindex{__copy__
} and
91 \method{__deepcopy__()
}\ttindex{__deepcopy__
}. The former is called to
92 implement the shallow copy operation; no additional arguments are
93 passed. The latter is called to implement the deep copy operation; it
94 is passed one argument, the memo dictionary. If the
95 \method{__deepcopy__()
} implementation needs to make a deep copy of a
96 component, it should call the
\function{deepcopy()
} function with the
97 component as first argument and the memo dictionary as second