1 \section{\module{copy
} ---
2 Shallow and deep copy operations
}
4 \declaremodule{standard
}{copy
}
5 \modulesynopsis{Shallow and deep copy operations.
}
8 This module provides generic (shallow and deep) copying operations.
9 \withsubitem{(in copy)
}{\ttindex{copy()
}\ttindex{deepcopy()
}}
16 x = copy.copy(y) # make a shallow copy of y
17 x = copy.deepcopy(y) # make a deep copy of y
20 For module specific errors,
\exception{copy.error
} is raised.
22 The difference between shallow and deep copying is only relevant for
23 compound objects (objects that contain other objects, like lists or
29 A
\emph{shallow copy
} constructs a new compound object and then (to the
30 extent possible) inserts
\emph{references
} into it to the objects found
34 A
\emph{deep copy
} constructs a new compound object and then,
35 recursively, inserts
\emph{copies
} into it of the objects found in the
40 Two problems often exist with deep copy operations that don't exist
41 with shallow copy operations:
46 Recursive objects (compound objects that, directly or indirectly,
47 contain a reference to themselves) may cause a recursive loop.
50 Because deep copy copies
\emph{everything
} it may copy too much,
51 e.g., administrative data structures that should be shared even
56 The
\function{deepcopy()
} function avoids these problems by:
61 keeping a ``memo'' dictionary of objects already copied during the current
65 letting user-defined classes override the copying operation or the
66 set of components copied.
70 This version does not copy types like module, class, function, method,
71 stack trace, stack frame, file, socket, window, array, or any similar
74 Classes can use the same interfaces to control copying that they use
75 to control pickling. See the description of module
76 \refmodule{pickle
}\refstmodindex{pickle
} for information on these
77 methods. The
\module{copy
} module does not use the
78 \refmodule[copyreg
]{copy_reg
} registration module.
80 In order for a class to define its own copy implementation, it can
81 define special methods
\method{__copy__()
} and
82 \method{__deepcopy__()
}. The former is called to implement the
83 shallow copy operation; no additional arguments are passed. The
84 latter is called to implement the deep copy operation; it is passed
85 one argument, the memo dictionary. If the
\method{__deepcopy__()
}
86 implementation needs to make a deep copy of a component, it should
87 call the
\function{deepcopy()
} function with the component as first
88 argument and the memo dictionary as second argument.
89 \withsubitem{(copy protocol)
}{\ttindex{__copy__()
}\ttindex{__deepcopy__()
}}
92 \seemodule{pickle
}{Discussion of the special methods used to
93 support object state retrieval and restoration.
}