Skip to content

Commit e88e1c8

Browse files
Improve the copy docs
1 parent d88a6b9 commit e88e1c8

10 files changed

Lines changed: 146 additions & 30 deletions

File tree

‎Doc/library/collections.rst‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1006,7 +1006,7 @@ field names, the method and attribute names start with an underscore.
10061006
>>> for partnum, record in inventory.items():
10071007
... inventory[partnum] = record._replace(price=newprices[partnum], timestamp=time.now())
10081008

1009-
Named tuples are also supported by generic function :func:`copy.replace`.
1009+
Named tuples also support :func:`copy.replace`.
10101010

10111011
.. versionchanged:: 3.13
10121012
Raise :exc:`TypeError` instead of :exc:`ValueError` for invalid

‎Doc/library/copy.rst‎

Lines changed: 133 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -12,35 +12,99 @@ Assignment statements in Python do not copy objects, they create bindings
1212
between a target and an object. For collections that are mutable or contain
1313
mutable items, a copy is sometimes needed so one can change one copy without
1414
changing 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+
44108
The difference between shallow and deep copying is only relevant for compound
45109
objects (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,
71135
file, socket, window, or any similar types. It does "copy" functions and
72136
classes (shallow and deeply), by returning the original object unchanged; this
73137
is 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

75141
Shallow 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
80146
when copying an instance of a subclass, whereas :func:`copy.copy` normally
81147
returns an instance of the same type.
82148

149+
150+
.. _copy-protocol:
151+
152+
Customizing copying
153+
-------------------
154+
83155
.. index:: pair: module; pickle
84156

85157
Classes 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-

‎Doc/library/dataclasses.rst‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -511,7 +511,7 @@ Module contents
511511
:func:`!replace` (or similarly named) method which handles instance
512512
copying.
513513

514-
Dataclass instances are also supported by generic function :func:`copy.replace`.
514+
Dataclass instances also support :func:`copy.replace`.
515515

516516
.. function:: is_dataclass(obj)
517517

‎Doc/library/datetime.rst‎

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -732,8 +732,7 @@ Instance methods:
732732
>>> d.replace(day=26)
733733
datetime.date(2002, 12, 26)
734734

735-
The generic function :func:`copy.replace` also supports :class:`date`
736-
objects.
735+
:class:`date` objects also support :func:`copy.replace`.
737736

738737

739738
.. method:: date.timetuple()
@@ -1391,8 +1390,7 @@ Instance methods:
13911390
to create a naive datetime from an aware datetime with no conversion of date
13921391
and time data.
13931392

1394-
:class:`.datetime` objects are also supported by generic function
1395-
:func:`copy.replace`.
1393+
:class:`.datetime` objects also support :func:`copy.replace`.
13961394

13971395
.. versionchanged:: 3.6
13981396
Added the *fold* parameter.
@@ -1996,8 +1994,7 @@ Instance methods:
19961994
naive :class:`!time` from an aware :class:`!time`, without conversion of the
19971995
time data.
19981996

1999-
:class:`.time` objects are also supported by generic function
2000-
:func:`copy.replace`.
1997+
:class:`.time` objects also support :func:`copy.replace`.
20011998

20021999
.. versionchanged:: 3.6
20032000
Added the *fold* parameter.

‎Doc/library/inspect.rst‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1002,8 +1002,7 @@ function.
10021002
>>> str(new_sig)
10031003
"(a, b) -> 'new return anno'"
10041004

1005-
:class:`Signature` objects are also supported by the generic function
1006-
:func:`copy.replace`.
1005+
:class:`Signature` objects also support :func:`copy.replace`.
10071006

10081007
.. method:: format(*, max_width=None, quote_annotation_strings=True)
10091008

@@ -1178,8 +1177,7 @@ function.
11781177
>>> str(param.replace(default=Parameter.empty, annotation='spam'))
11791178
"foo: 'spam'"
11801179

1181-
:class:`Parameter` objects are also supported by the generic function
1182-
:func:`copy.replace`.
1180+
:class:`Parameter` objects also support :func:`copy.replace`.
11831181

11841182
.. versionchanged:: 3.4
11851183
In Python 3.3 :class:`Parameter` objects were allowed to have ``name`` set

‎Doc/library/pickle.rst‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1255,7 +1255,7 @@ The following option is accepted:
12551255
:exc:`AttributeError` but it could be something else.
12561256
12571257
.. [#] The :mod:`copy` module uses this protocol for shallow and deep copying
1258-
operations.
1258+
operations; see :ref:`copy-protocol`.
12591259
12601260
.. [#] The limitation on alphanumeric characters is due to the fact
12611261
that persistent IDs in protocol 0 are delimited by the newline

‎Doc/library/re.rst‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1645,7 +1645,7 @@ Regular expression objects
16451645

16461646

16471647
.. versionchanged:: 3.7
1648-
Added support of :func:`copy.copy` and :func:`copy.deepcopy`. Compiled
1648+
Added support for :func:`copy.copy` and :func:`copy.deepcopy`. Compiled
16491649
regular expression objects are considered atomic.
16501650

16511651

@@ -1867,7 +1867,7 @@ when there is no match, you can test whether there was a match with a simple
18671867

18681868

18691869
.. versionchanged:: 3.7
1870-
Added support of :func:`copy.copy` and :func:`copy.deepcopy`. Match objects
1870+
Added support for :func:`copy.copy` and :func:`copy.deepcopy`. Match objects
18711871
are considered atomic.
18721872

18731873

‎Doc/library/tarfile.rst‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -776,7 +776,7 @@ It does *not* contain the file's data itself.
776776
Modifying the objects returned by :meth:`~TarFile.getmember` or
777777
:meth:`~TarFile.getmembers` will affect all subsequent
778778
operations on the archive.
779-
For cases where this is unwanted, you can use :mod:`copy.copy() <copy>` or
779+
For cases where this is unwanted, you can use :func:`copy.copy` or
780780
call the :meth:`~TarInfo.replace` method to create a modified copy in one step.
781781

782782
Several attributes can be set to ``None`` to indicate that a piece of metadata

‎Doc/library/types.rst‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -504,7 +504,7 @@ Additional Utility Classes and Functions
504504
However, for a structured record type use :func:`~collections.namedtuple`
505505
instead.
506506

507-
:class:`!SimpleNamespace` objects are supported by :func:`copy.replace`.
507+
:class:`!SimpleNamespace` objects support :func:`copy.replace`.
508508

509509
.. versionadded:: 3.3
510510

‎Doc/reference/datamodel.rst‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1673,7 +1673,7 @@ Methods on code objects
16731673

16741674
Return a copy of the code object with new values for the specified fields.
16751675

1676-
Code objects are also supported by the generic function :func:`copy.replace`.
1676+
Code objects also support :func:`copy.replace`.
16771677

16781678
.. versionadded:: 3.8
16791679

0 commit comments

Comments
 (0)