Repository navigation
Docs: Improve the copy module documentation
#162818
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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): | ||
|
|
||
|
|
@@ -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,12 +146,11 @@ 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. | ||
|
|
||
| .. index:: pair: module; pickle | ||
|
|
||
| Classes can use the same interfaces to control copying that they use to control | ||
| pickling. See the description of module :mod:`pickle` for information on these | ||
| methods. In fact, the :mod:`!copy` module uses the registered | ||
| pickle functions from the :mod:`copyreg` module. | ||
| .. _copy-protocol: | ||
|
|
||
| Customizing copying | ||
| ------------------- | ||
|
|
||
| .. index:: | ||
| single: __copy__() (copy protocol) | ||
|
|
@@ -111,27 +176,93 @@ 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:: pair: module; pickle | ||
|
|
||
| A class which defines neither :meth:`~object.__copy__` nor | ||
| :meth:`~object.__deepcopy__` is copied using the same interfaces that | ||
| control pickling. | ||
| The :mod:`!copy` module first looks for a function registered for the class | ||
| with :func:`copyreg.pickle`, and otherwise calls the object's | ||
| :meth:`~object.__reduce_ex__` method with protocol 4. | ||
| The new object is then created from the returned value, and its state is | ||
| restored with :meth:`~object.__setstate__` if the class defines it. | ||
| A deep copy also deep copies the arguments and state in the returned value. | ||
| This means that the :meth:`~object.__getnewargs_ex__`, | ||
| :meth:`~object.__getstate__` and :meth:`~object.__setstate__` methods | ||
| customize both pickling and copying. | ||
| See the description of module :mod:`pickle` for information on these methods. | ||
|
|
||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can we move this paragraph down and/or give it a dedicated subsection header? Right now, if you look at the rendered page (not this source), there's not much separation. So you see the doctest above, then this text, and then the following sentence ("In order for a class to support |
||
|
|
||
| .. 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. | ||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.