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/optparse.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1073,6 +1073,12 @@ As you can see, most actions involve storing or updating a value somewhere.
and can be overridden by a custom subclass passed to the *values* argument of
:meth:`OptionParser.parse_args` (as described in :ref:`optparse-parsing-arguments`).

:class:`!Values` 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`.

Option
arguments (and various other values) are stored as attributes of this object,
according to the :attr:`~Option.dest` (destination) option attribute.
Expand Down
6 changes: 6 additions & 0 deletions Lib/optparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -830,6 +830,12 @@ def __eq__(self, other):
else:
return NotImplemented

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

def _update_careful(self, dict):
"""
Update the option values from an arbitrary dictionary, but only
Expand Down
7 changes: 7 additions & 0 deletions Lib/test/test_optparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,13 @@ def test_basics(self):
self.assertNotEqual(values, "")
self.assertNotEqual(values, [])

def test_replace(self):
values = Values(defaults={"foo": "bar", "baz": 42})
new = copy.replace(values, baz=43, spam="eggs")
self.assertIsInstance(new, Values)
self.assertEqual(vars(new), {"foo": "bar", "baz": 43, "spam": "eggs"})
self.assertEqual(vars(values), {"foo": "bar", "baz": 42})


class TestTypeAliases(BaseTest):
def setUp(self):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
:class:`optparse.Values` objects now support :func:`copy.replace`.
Loading