@@ -12,35 +12,99 @@ Assignment statements in Python do not copy objects, they create bindings
1212between a target and an object. For collections that are mutable or contain
1313mutable items, a copy is sometimes needed so one can change one copy without
1414changing the other. This module provides generic shallow and deep copy
15- operations (explained below) .
15+ operations, and a function to create a modified copy of an object .
1616
17+ After an assignment, both names refer to the same list, so a change made
18+ through one name is visible through the other:
1719
18- Interface summary:
20+ .. doctest ::
21+
22+ >>> colors = [' red' , ' green' ]
23+ >>> same_list = colors
24+ >>> colors.append(' blue' )
25+ >>> same_list
26+ ['red', 'green', 'blue']
27+
28+ To get a separate list, use :func: `copy.copy `:
29+
30+ .. doctest ::
31+
32+ >>> import copy
33+ >>> new_list = copy.copy(colors)
34+ >>> colors.append(' yellow' )
35+ >>> new_list
36+ ['red', 'green', 'blue']
37+
38+ :func: `copy.copy ` makes a *shallow * copy: the new list is a separate object,
39+ but it contains the same items as the original.
40+ This matters when the items can themselves be changed:
41+
42+ .. doctest ::
43+
44+ >>> rows = [[1 , 2 ], [3 , 4 ]]
45+ >>> shallow = copy.copy(rows)
46+ >>> rows[0 ].append(' new' )
47+ >>> shallow
48+ [[1, 2, 'new'], [3, 4]]
49+
50+ To copy the inner lists as well, use :func: `copy.deepcopy `:
51+
52+ .. doctest ::
53+
54+ >>> rows = [[1 , 2 ], [3 , 4 ]]
55+ >>> deep = copy.deepcopy(rows)
56+ >>> rows[0 ].append(' new' )
57+ >>> deep
58+ [[1, 2], [3, 4]]
59+
60+
61+ Functions
62+ ---------
1963
2064.. function :: copy(obj)
2165
22- Return a shallow copy of *obj *.
66+ Return a :ref: `shallow copy <shallow_vs_deep_copy >` of *obj *.
67+
2368
69+ .. function :: deepcopy(obj, memo=None)
2470
25- .. function :: deepcopy(obj[, memo])
71+ Return a :ref: ` deep copy < shallow_vs_deep_copy >` of * obj *.
2672
27- Return a deep copy of *obj *.
73+ The *memo * dictionary records the objects already copied.
74+ It should only be passed by an :meth: `~object.__deepcopy__ ` method.
2875
2976
3077.. function :: replace(obj, /, **changes)
3178
32- Creates a new object of the same type as *obj *, replacing fields with values
79+ Return a new object of the same type as *obj *, replacing fields with values
3380 from *changes *.
3481
82+ This function is more limited than :func: `copy ` and :func: `deepcopy `.
83+ It only supports named tuples created by :func: `~collections.namedtuple `,
84+ :mod: `dataclasses `, and other classes which define the
85+ :meth: `~object.__replace__ ` method.
86+ A :exc: `TypeError ` is raised for other objects.
87+
88+ .. doctest ::
89+
90+ >>> from collections import namedtuple
91+ >>> Point = namedtuple(' Point' , [' x' , ' y' ])
92+ >>> copy.replace(Point(1 , 2 ), y = 5 )
93+ Point(x=1, y=5)
94+
3595 .. versionadded :: 3.13
3696
3797
3898.. exception :: Error
3999
40100 Raised for module specific errors.
41101
102+
42103.. _shallow_vs_deep_copy :
43104
105+ Shallow and deep copies
106+ -----------------------
107+
44108The difference between shallow and deep copying is only relevant for compound
45109objects (objects that contain other objects, like lists or class instances):
46110
@@ -67,10 +131,12 @@ The :func:`deepcopy` function avoids these problems by:
67131* letting user-defined classes override the copying operation or the set of
68132 components copied.
69133
70- This module does not copy types like module, method, stack trace, stack frame,
134+ This module does not copy types like module, stack trace, stack frame,
71135file, socket, window, or any similar types. It does "copy" functions and
72136classes (shallow and deeply), by returning the original object unchanged; this
73137is compatible with the way these are treated by the :mod: `pickle ` module.
138+ Immutable built-in objects like numbers and strings are also returned
139+ unchanged.
74140
75141Shallow copies of many collections can be made using the corresponding
76142:meth: `!copy ` method (such as :meth: `list.copy `, :meth: `dict.copy ` or
@@ -80,6 +146,12 @@ However, these methods and slicing can create an instance of the base type
80146when copying an instance of a subclass, whereas :func: `copy.copy ` normally
81147returns an instance of the same type.
82148
149+
150+ .. _copy-protocol :
151+
152+ Customizing copying
153+ -------------------
154+
83155.. index :: pair: module; pickle
84156
85157Classes can use the same interfaces to control copying that they use to control
@@ -111,27 +183,76 @@ special methods :meth:`~object.__copy__` and :meth:`~object.__deepcopy__`.
111183 with the component as first argument and the *memo * dictionary as second argument.
112184 The *memo * dictionary should be treated as an opaque object.
113185
186+ In this example, a shallow copy of a ``Playlist `` gets its own list of songs,
187+ and a deep copy shares the ``library `` with the original:
188+
189+ .. testcode ::
190+
191+ import copy
192+
193+ class Playlist:
194+ def __init__(self, songs, library):
195+ self.songs = songs
196+ self.library = library
197+
198+ def __copy__(self):
199+ return type(self)(list(self.songs), self.library)
200+
201+ def __deepcopy__(self, memo):
202+ songs = copy.deepcopy(self.songs, memo)
203+ return type(self)(songs, self.library)
204+
205+ .. doctest ::
206+
207+ >>> library = {' Brave Sir Robin' : ' robin.mp3' }
208+ >>> original = Playlist([' Brave Sir Robin' ], library)
209+ >>> shallow = copy.copy(original)
210+ >>> shallow.songs is original.songs
211+ False
212+ >>> deep = copy.deepcopy(original)
213+ >>> deep.library is original.library
214+ True
215+
114216
115217.. index ::
116218 single: __replace__() (replace protocol)
117219
118- Function :func: `!copy.replace ` is more limited
119- than :func: `~copy.copy ` and :func: `~copy.deepcopy `,
120- and only supports named tuples created by :func: `~collections.namedtuple `,
121- :mod: `dataclasses `, and other classes which define method :meth: `~object.__replace__ `.
220+ In order for a class to support :func: `copy.replace `,
221+ it can define the special method :meth: `~object.__replace__ `.
122222
123223.. method :: object.__replace__(self, /, **changes)
124224 :noindexentry:
125225
226+ Called to implement :func: `copy.replace `.
126227 This method should create a new object of the same type,
127228 replacing fields with values from *changes *.
128229
129230 .. versionadded :: 3.13
130231
232+ In this example, ``copy.replace() `` works for instances of ``Point ``:
233+
234+ .. testcode ::
235+
236+ import copy
237+
238+ class Point:
239+ def __init__(self, x, y):
240+ self.x = x
241+ self.y = y
242+
243+ def __replace__(self, /, **changes):
244+ fields = {'x': self.x, 'y': self.y} | changes
245+ return type(self)(**fields)
246+
247+ .. doctest ::
248+
249+ >>> point = copy.replace(Point(1 , 2 ), y = 5 )
250+ >>> point.x, point.y
251+ (1, 5)
252+
131253
132254.. seealso ::
133255
134256 Module :mod: `pickle `
135257 Discussion of the special methods used to support object state retrieval and
136258 restoration.
137-
0 commit comments