diff --git a/Doc/library/collections.rst b/Doc/library/collections.rst index 40f780c7d049d4..dceea0463af71a 100644 --- a/Doc/library/collections.rst +++ b/Doc/library/collections.rst @@ -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 diff --git a/Doc/library/copy.rst b/Doc/library/copy.rst index 39fc7800d03a91..0e771adf71d1aa 100644 --- a/Doc/library/copy.rst +++ b/Doc/library/copy.rst @@ -12,26 +12,86 @@ 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 ` of *obj*. + +.. function:: deepcopy(obj, memo=None) -.. function:: deepcopy(obj[, memo]) + Return a :ref:`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 @@ -39,8 +99,12 @@ Interface summary: 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): @@ -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 @@ -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 @@ -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. - diff --git a/Doc/library/dataclasses.rst b/Doc/library/dataclasses.rst index ec8c913072487a..f41d8d6519d4a1 100644 --- a/Doc/library/dataclasses.rst +++ b/Doc/library/dataclasses.rst @@ -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) diff --git a/Doc/library/datetime.rst b/Doc/library/datetime.rst index 20d6f0cb9d4abf..5cb5b0c90a4fe6 100644 --- a/Doc/library/datetime.rst +++ b/Doc/library/datetime.rst @@ -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() @@ -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. @@ -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. diff --git a/Doc/library/inspect.rst b/Doc/library/inspect.rst index 51c465e8f00b5e..f090898211b342 100644 --- a/Doc/library/inspect.rst +++ b/Doc/library/inspect.rst @@ -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) @@ -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 diff --git a/Doc/library/pickle.rst b/Doc/library/pickle.rst index 30073dfc5028df..aa494fed5ffe11 100644 --- a/Doc/library/pickle.rst +++ b/Doc/library/pickle.rst @@ -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 diff --git a/Doc/library/re.rst b/Doc/library/re.rst index c9f27fd02988f8..cc49c9132d8b23 100644 --- a/Doc/library/re.rst +++ b/Doc/library/re.rst @@ -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. @@ -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. diff --git a/Doc/library/tarfile.rst b/Doc/library/tarfile.rst index 3131107be97189..3ac87c10f2b720 100644 --- a/Doc/library/tarfile.rst +++ b/Doc/library/tarfile.rst @@ -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() ` 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 diff --git a/Doc/library/types.rst b/Doc/library/types.rst index 7a6e7aa3fae6a5..66aff118d0d940 100644 --- a/Doc/library/types.rst +++ b/Doc/library/types.rst @@ -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 diff --git a/Doc/reference/datamodel.rst b/Doc/reference/datamodel.rst index 02663ed465f424..1381dc5f7d4488 100644 --- a/Doc/reference/datamodel.rst +++ b/Doc/reference/datamodel.rst @@ -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