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
6 changes: 6 additions & 0 deletions Doc/library/argparse.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1679,6 +1679,12 @@ The Namespace object
Simple class used by default by :meth:`~ArgumentParser.parse_args` to create
an object holding attributes and return it.

:class:`!Namespace` objects support :func:`copy.replace`,
which returns a copy of the object with the specified attributes replaced.

.. versionchanged:: next
Added support for :func:`copy.replace`.

This class is deliberately simple, just an :class:`object` subclass with a
readable string representation. If you prefer to have dict-like view of the
attributes, you can use the standard Python idiom, :func:`vars`::
Expand Down
6 changes: 6 additions & 0 deletions Lib/argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -1545,6 +1545,12 @@ def __eq__(self, other):
def __contains__(self, key):
return key in self.__dict__

def __replace__(self, /, **changes):
new = self.__class__()
new.__dict__.update(self.__dict__)
new.__dict__.update(changes)
return new


class _ActionsContainer(object):

Expand Down
14 changes: 14 additions & 0 deletions Lib/test/test_argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import _colorize
import contextlib
import copy
import functools
import io
import operator
Expand Down Expand Up @@ -6267,6 +6268,19 @@ def test_equality_returns_notimplemented(self):
self.assertIs(ns.__eq__(None), NotImplemented)
self.assertIs(ns.__ne__(None), NotImplemented)

def test_replace(self):
ns = argparse.Namespace(a=1, b=2)
new = copy.replace(ns, b=3, c=4)
self.assertIsInstance(new, argparse.Namespace)
self.assertEqual(new, argparse.Namespace(a=1, b=3, c=4))
self.assertEqual(ns, argparse.Namespace(a=1, b=2))

class MyNamespace(argparse.Namespace):
pass
new = copy.replace(MyNamespace(a=1), a=2)
self.assertIsInstance(new, MyNamespace)
self.assertEqual(new.a, 2)


# ===================
# File encoding tests
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
:class:`argparse.Namespace` objects now support :func:`copy.replace`.
Loading