summaryrefslogtreecommitdiffstats
path: root/Doc/library/copy.rst
diff options
context:
space:
mode:
authorSerhiy Storchaka <storchaka@gmail.com>2023-09-06 20:55:42 (GMT)
committerGitHub <noreply@github.com>2023-09-06 20:55:42 (GMT)
commit6f3c138dfa868b32d3288898923bbfa388f2fa5d (patch)
tree98098db4d0d2f256f2a17d515c1750a28424166c /Doc/library/copy.rst
parent9f0c0a46f00d687e921990ee83894b2f4ce8a6e7 (diff)
downloadcpython-6f3c138dfa868b32d3288898923bbfa388f2fa5d.zip
cpython-6f3c138dfa868b32d3288898923bbfa388f2fa5d.tar.gz
cpython-6f3c138dfa868b32d3288898923bbfa388f2fa5d.tar.bz2
gh-108751: Add copy.replace() function (GH-108752)
It creates a modified copy of an object by calling the object's __replace__() method. It is a generalization of dataclasses.replace(), named tuple's _replace() method and replace() methods in various classes, and supports all these stdlib classes.
Diffstat (limited to 'Doc/library/copy.rst')
-rw-r--r--Doc/library/copy.rst30
1 files changed, 26 insertions, 4 deletions
diff --git a/Doc/library/copy.rst b/Doc/library/copy.rst
index 8f32477..cc4ca03 100644
--- a/Doc/library/copy.rst
+++ b/Doc/library/copy.rst
@@ -17,14 +17,22 @@ operations (explained below).
Interface summary:
-.. function:: copy(x)
+.. function:: copy(obj)
- Return a shallow copy of *x*.
+ Return a shallow copy of *obj*.
-.. function:: deepcopy(x[, memo])
+.. function:: deepcopy(obj[, memo])
- Return a deep copy of *x*.
+ Return a deep copy of *obj*.
+
+
+.. function:: replace(obj, /, **changes)
+
+ Creates a new object of the same type as *obj*, replacing fields with values
+ from *changes*.
+
+ .. versionadded:: 3.13
.. exception:: Error
@@ -89,6 +97,20 @@ with the component as first argument and the memo dictionary as second argument.
The memo dictionary should be treated as an opaque object.
+.. index::
+ single: __replace__() (replace protocol)
+
+Function :func:`replace` is more limited than :func:`copy` and :func:`deepcopy`,
+and only supports named tuples created by :func:`~collections.namedtuple`,
+:mod:`dataclasses`, and other classes which define method :meth:`!__replace__`.
+
+ .. method:: __replace__(self, /, **changes)
+ :noindex:
+
+:meth:`!__replace__` should create a new object of the same type,
+replacing fields with values from *changes*.
+
+
.. seealso::
Module :mod:`pickle`