Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Doc/library/collections.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1006,7 +1006,7 @@ field names, the method and attribute names start with an underscore.
>>> for partnum, record in inventory.items():
... inventory[partnum] = record._replace(price=newprices[partnum], timestamp=time.now())

Named tuples are also supported by generic function :func:`copy.replace`.
Named tuples also support :func:`copy.replace`.

.. versionchanged:: 3.13
Raise :exc:`TypeError` instead of :exc:`ValueError` for invalid
Expand Down
145 changes: 133 additions & 12 deletions Doc/library/copy.rst
Original file line number Diff line number Diff line change
Expand Up @@ -12,35 +12,99 @@ Assignment statements in Python do not copy objects, they create bindings
between a target and an object. For collections that are mutable or contain
mutable items, a copy is sometimes needed so one can change one copy without
changing the other. This module provides generic shallow and deep copy
operations (explained below).
operations, and a function to create a modified copy of an object.

After an assignment, both names refer to the same list, so a change made
through one name is visible through the other:

Interface summary:
.. doctest::

>>> colors = ['red', 'green']
>>> same_list = colors
>>> colors.append('blue')
>>> same_list
['red', 'green', 'blue']

To get a separate list, use :func:`copy.copy`:

.. doctest::

>>> import copy
>>> new_list = copy.copy(colors)
>>> colors.append('yellow')
>>> new_list
['red', 'green', 'blue']

:func:`copy.copy` makes a *shallow* copy: the new list is a separate object,
but it contains the same items as the original.
This matters when the items can themselves be changed:

.. doctest::

>>> rows = [[1, 2], [3, 4]]
>>> shallow = copy.copy(rows)
>>> rows[0].append('new')
>>> shallow
[[1, 2, 'new'], [3, 4]]

To copy the inner lists as well, use :func:`copy.deepcopy`:

.. doctest::

>>> rows = [[1, 2], [3, 4]]
>>> deep = copy.deepcopy(rows)
>>> rows[0].append('new')
>>> deep
[[1, 2], [3, 4]]


Functions
---------

.. function:: copy(obj)

Return a shallow copy of *obj*.
Return a :ref:`shallow copy <shallow_vs_deep_copy>` of *obj*.


.. function:: deepcopy(obj, memo=None)

.. function:: deepcopy(obj[, memo])
Return a :ref:`deep copy <shallow_vs_deep_copy>` of *obj*.

Return a deep copy of *obj*.
The *memo* dictionary records the objects already copied.
It should only be passed by an :meth:`~object.__deepcopy__` method.


.. function:: replace(obj, /, **changes)

Creates a new object of the same type as *obj*, replacing fields with values
Return a new object of the same type as *obj*, replacing fields with values
from *changes*.

This function is more limited than :func:`copy` and :func:`deepcopy`.
It only supports named tuples created by :func:`~collections.namedtuple`,
:mod:`dataclasses`, and other classes which define the
:meth:`~object.__replace__` method.
A :exc:`TypeError` is raised for other objects.

.. doctest::

>>> from collections import namedtuple
>>> Point = namedtuple('Point', ['x', 'y'])
>>> copy.replace(Point(1, 2), y=5)
Point(x=1, y=5)

.. versionadded:: 3.13


.. exception:: Error

Raised for module specific errors.


.. _shallow_vs_deep_copy:

Shallow and deep copies
-----------------------

The difference between shallow and deep copying is only relevant for compound
objects (objects that contain other objects, like lists or class instances):

Expand All @@ -67,10 +131,12 @@ The :func:`deepcopy` function avoids these problems by:
* letting user-defined classes override the copying operation or the set of
components copied.

This module does not copy types like module, method, stack trace, stack frame,
This module does not copy types like module, stack trace, stack frame,
file, socket, window, or any similar types. It does "copy" functions and
classes (shallow and deeply), by returning the original object unchanged; this
is compatible with the way these are treated by the :mod:`pickle` module.
Immutable built-in objects like numbers and strings are also returned
unchanged.

Shallow copies of many collections can be made using the corresponding
:meth:`!copy` method (such as :meth:`list.copy`, :meth:`dict.copy` or
Expand All @@ -80,6 +146,12 @@ However, these methods and slicing can create an instance of the base type
when copying an instance of a subclass, whereas :func:`copy.copy` normally
returns an instance of the same type.


.. _copy-protocol:

Customizing copying
-------------------

.. index:: pair: module; pickle

Classes can use the same interfaces to control copying that they use to control
Expand Down Expand Up @@ -111,27 +183,76 @@ special methods :meth:`~object.__copy__` and :meth:`~object.__deepcopy__`.
with the component as first argument and the *memo* dictionary as second argument.
The *memo* dictionary should be treated as an opaque object.

In this example, a shallow copy of a ``Playlist`` gets its own list of songs,
and a deep copy shares the ``library`` with the original:

.. testcode::

import copy

class Playlist:
def __init__(self, songs, library):
self.songs = songs
self.library = library

def __copy__(self):
return type(self)(list(self.songs), self.library)

def __deepcopy__(self, memo):
songs = copy.deepcopy(self.songs, memo)
return type(self)(songs, self.library)

.. doctest::

>>> library = {'Brave Sir Robin': 'robin.mp3'}
>>> original = Playlist(['Brave Sir Robin'], library)
>>> shallow = copy.copy(original)
>>> shallow.songs is original.songs
False
>>> deep = copy.deepcopy(original)
>>> deep.library is original.library
True


.. index::
single: __replace__() (replace protocol)

Function :func:`!copy.replace` is more limited
than :func:`~copy.copy` and :func:`~copy.deepcopy`,
and only supports named tuples created by :func:`~collections.namedtuple`,
:mod:`dataclasses`, and other classes which define method :meth:`~object.__replace__`.
In order for a class to support :func:`copy.replace`,
it can define the special method :meth:`~object.__replace__`.

.. method:: object.__replace__(self, /, **changes)
:noindexentry:

Called to implement :func:`copy.replace`.
This method should create a new object of the same type,
replacing fields with values from *changes*.

.. versionadded:: 3.13

In this example, ``copy.replace()`` works for instances of ``Point``:

.. testcode::

import copy

class Point:
def __init__(self, x, y):
self.x = x
self.y = y

def __replace__(self, /, **changes):
fields = {'x': self.x, 'y': self.y} | changes
return type(self)(**fields)

.. doctest::

>>> point = copy.replace(Point(1, 2), y=5)
>>> point.x, point.y
(1, 5)


.. seealso::

Module :mod:`pickle`
Discussion of the special methods used to support object state retrieval and
restoration.

2 changes: 1 addition & 1 deletion Doc/library/dataclasses.rst
Original file line number Diff line number Diff line change
Expand Up @@ -511,7 +511,7 @@ Module contents
:func:`!replace` (or similarly named) method which handles instance
copying.

Dataclass instances are also supported by generic function :func:`copy.replace`.
Dataclass instances also support :func:`copy.replace`.

.. function:: is_dataclass(obj)

Expand Down
9 changes: 3 additions & 6 deletions Doc/library/datetime.rst
Original file line number Diff line number Diff line change
Expand Up @@ -732,8 +732,7 @@ Instance methods:
>>> d.replace(day=26)
datetime.date(2002, 12, 26)

The generic function :func:`copy.replace` also supports :class:`date`
objects.
:class:`date` objects also support :func:`copy.replace`.


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

:class:`.datetime` objects are also supported by generic function
:func:`copy.replace`.
:class:`.datetime` objects also support :func:`copy.replace`.

.. versionchanged:: 3.6
Added the *fold* parameter.
Expand Down Expand Up @@ -1996,8 +1994,7 @@ Instance methods:
naive :class:`!time` from an aware :class:`!time`, without conversion of the
time data.

:class:`.time` objects are also supported by generic function
:func:`copy.replace`.
:class:`.time` objects also support :func:`copy.replace`.

.. versionchanged:: 3.6
Added the *fold* parameter.
Expand Down
6 changes: 2 additions & 4 deletions Doc/library/inspect.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1002,8 +1002,7 @@ function.
>>> str(new_sig)
"(a, b) -> 'new return anno'"

:class:`Signature` objects are also supported by the generic function
:func:`copy.replace`.
:class:`Signature` objects also support :func:`copy.replace`.

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

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

:class:`Parameter` objects are also supported by the generic function
:func:`copy.replace`.
:class:`Parameter` objects also support :func:`copy.replace`.

.. versionchanged:: 3.4
In Python 3.3 :class:`Parameter` objects were allowed to have ``name`` set
Expand Down
2 changes: 1 addition & 1 deletion Doc/library/pickle.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1255,7 +1255,7 @@ The following option is accepted:
:exc:`AttributeError` but it could be something else.

.. [#] The :mod:`copy` module uses this protocol for shallow and deep copying
operations.
operations; see :ref:`copy-protocol`.

.. [#] The limitation on alphanumeric characters is due to the fact
that persistent IDs in protocol 0 are delimited by the newline
Expand Down
4 changes: 2 additions & 2 deletions Doc/library/re.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1645,7 +1645,7 @@ Regular expression objects


.. versionchanged:: 3.7
Added support of :func:`copy.copy` and :func:`copy.deepcopy`. Compiled
Added support for :func:`copy.copy` and :func:`copy.deepcopy`. Compiled
regular expression objects are considered atomic.


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


.. versionchanged:: 3.7
Added support of :func:`copy.copy` and :func:`copy.deepcopy`. Match objects
Added support for :func:`copy.copy` and :func:`copy.deepcopy`. Match objects
are considered atomic.


Expand Down
2 changes: 1 addition & 1 deletion Doc/library/tarfile.rst
Original file line number Diff line number Diff line change
Expand Up @@ -776,7 +776,7 @@ It does *not* contain the file's data itself.
Modifying the objects returned by :meth:`~TarFile.getmember` or
:meth:`~TarFile.getmembers` will affect all subsequent
operations on the archive.
For cases where this is unwanted, you can use :mod:`copy.copy() <copy>` or
For cases where this is unwanted, you can use :func:`copy.copy` or
call the :meth:`~TarInfo.replace` method to create a modified copy in one step.

Several attributes can be set to ``None`` to indicate that a piece of metadata
Expand Down
2 changes: 1 addition & 1 deletion Doc/library/types.rst
Original file line number Diff line number Diff line change
Expand Up @@ -504,7 +504,7 @@ Additional Utility Classes and Functions
However, for a structured record type use :func:`~collections.namedtuple`
instead.

:class:`!SimpleNamespace` objects are supported by :func:`copy.replace`.
:class:`!SimpleNamespace` objects support :func:`copy.replace`.

.. versionadded:: 3.3

Expand Down
2 changes: 1 addition & 1 deletion Doc/reference/datamodel.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1673,7 +1673,7 @@ Methods on code objects

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

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

.. versionadded:: 3.8

Expand Down
Loading