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