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