blob: f7f9744a099b9b18cb909b1f438e0263de8089b6 [file] [log] [blame]
Guido van Rossumd1883581995-02-15 15:53:08 +00001\section{Built-in module \sectcode{copy}}
2\stmodindex{copy}
3\ttindex{copy}
4\ttindex{deepcopy}
5
6This module provides generic (shallow and deep) copying operations.
7
8Interface summary:
9
10\begin{verbatim}
11import copy
12
13x = copy.copy(y) # make a shallow copy of y
14x = copy.deepcopy(y) # make a deep copy of y
15\end{verbatim}
16
17For module specific errors, \code{copy.Error} is raised.
18
19The difference between shallow and deep copying is only relevant for
20compound objects (objects that contain other objects, like lists or
21class instances):
22
23\begin{itemize}
24
25\item
26A {\em shallow copy} constructs a new compound object and then (to the
27extent possible) inserts {\em references} into it to the objects found
28in the original.
29
30\item
31A {\em deep copy} constructs a new compound object and then,
32recursively, inserts {\em copies} into it of the objects found in the
33original.
34
35\end{itemize}
36
37Two problems often exist with deep copy operations that don't exist
38with shallow copy operations:
39
40\begin{itemize}
41
42\item
43Recursive objects (compound objects that, directly or indirectly,
44contain a reference to themselves) may cause a recursive loop.
45
46\item
47Because deep copy copies {\em everything} it may copy too much, e.g.
48administrative data structures that should be shared even between
49copies.
50
51\end{itemize}
52
53Python's \code{deepcopy()} operation avoids these problems by:
54
55\begin{itemize}
56
57\item
58keeping a table of objects already copied during the current
59copying pass; and
60
61\item
62letting user-defined classes override the copying operation or the
63set of components copied.
64
65\end{itemize}
66
67This version does not copy types like module, class, function, method,
68nor stack trace, stack frame, nor file, socket, window, nor array, nor
69any similar types.
70
71Classes can use the same interfaces to control copying that they use
72to control pickling: they can define methods called
73\code{__getinitargs__()}, \code{__getstate__()} and
74\code{__setstate__()}. See the description of module \code{pickle}
75for information on these methods.
76\stmodindex{pickle}
77\ttindex{__getinitargs__}
78\ttindex{__getstate__}
79\ttindex{__setstate__}