Skip to content

Commit 9dc11d8

Browse files
gh-155043: Support copy.replace() for argparse.Namespace (#155049)
1 parent dd5a285 commit 9dc11d8

4 files changed

Lines changed: 27 additions & 0 deletions

File tree

Doc/library/argparse.rst

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1679,6 +1679,12 @@ The Namespace object
16791679
Simple class used by default by :meth:`~ArgumentParser.parse_args` to create
16801680
an object holding attributes and return it.
16811681

1682+
:class:`!Namespace` objects support :func:`copy.replace`,
1683+
which returns a copy of the object with the specified attributes replaced.
1684+
1685+
.. versionchanged:: next
1686+
Added support for :func:`copy.replace`.
1687+
16821688
This class is deliberately simple, just an :class:`object` subclass with a
16831689
readable string representation. If you prefer to have dict-like view of the
16841690
attributes, you can use the standard Python idiom, :func:`vars`::

Lib/argparse.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1545,6 +1545,12 @@ def __eq__(self, other):
15451545
def __contains__(self, key):
15461546
return key in self.__dict__
15471547

1548+
def __replace__(self, /, **changes):
1549+
new = self.__class__()
1550+
new.__dict__.update(self.__dict__)
1551+
new.__dict__.update(changes)
1552+
return new
1553+
15481554

15491555
class _ActionsContainer(object):
15501556

Lib/test/test_argparse.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import _colorize
44
import contextlib
5+
import copy
56
import functools
67
import io
78
import operator
@@ -6267,6 +6268,19 @@ def test_equality_returns_notimplemented(self):
62676268
self.assertIs(ns.__eq__(None), NotImplemented)
62686269
self.assertIs(ns.__ne__(None), NotImplemented)
62696270

6271+
def test_replace(self):
6272+
ns = argparse.Namespace(a=1, b=2)
6273+
new = copy.replace(ns, b=3, c=4)
6274+
self.assertIsInstance(new, argparse.Namespace)
6275+
self.assertEqual(new, argparse.Namespace(a=1, b=3, c=4))
6276+
self.assertEqual(ns, argparse.Namespace(a=1, b=2))
6277+
6278+
class MyNamespace(argparse.Namespace):
6279+
pass
6280+
new = copy.replace(MyNamespace(a=1), a=2)
6281+
self.assertIsInstance(new, MyNamespace)
6282+
self.assertEqual(new.a, 2)
6283+
62706284

62716285
# ===================
62726286
# File encoding tests
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
:class:`argparse.Namespace` objects now support :func:`copy.replace`.

0 commit comments

Comments
 (0)