Skip to content

bpo-43160: Add extend_const action to argparse #24478

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

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
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
15 changes: 15 additions & 0 deletions Doc/library/argparse.rst
Original file line number Diff line number Diff line change
Expand Up @@ -842,6 +842,21 @@ how the command-line arguments should be handled. The supplied actions are:

.. versionadded:: 3.8

* ``'extend_const'`` - This stores a list, and extends each argument value to the list.
The ``'extend_const'`` action is typically useful when you want to provide an alias
that is the combination of multiple other arguments. For example::

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--str', dest='types', action='append_const', const=str)
>>> parser.add_argument('--int', dest='types', action='append_const', const=int)
>>> parser.add_argument('--both', dest='types', action='extend_const', const=(str, int))
>>> parser.parse_args('--str --int'.split())
Namespace(types=[<class 'str'>, <class 'int'>])
>>> parser.parse_args('--both'.split())
Namespace(types=[<class 'str'>, <class 'int'>])

.. versionadded:: TBA

You may also specify an arbitrary action by passing an Action subclass or
other object that implements the same interface. The ``BooleanOptionalAction``
is available in ``argparse`` and adds support for boolean actions such as
Expand Down
13 changes: 11 additions & 2 deletions Lib/argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,8 +138,9 @@ def _get_args(self):
def _copy_items(items):
if items is None:
return []
# The copy module is used only in the 'append' and 'append_const'
# actions, and it is needed only when the default value isn't a list.
# The copy module is used in the 'append', 'append_const', 'extend', and
# 'extend_const' actions, and it is needed only when the default value
# isn't a list.
# Delay its import for speeding up the common case.
if type(items) is list:
return items[:]
Expand Down Expand Up @@ -1219,6 +1220,13 @@ def __call__(self, parser, namespace, values, option_string=None):
items.extend(values)
setattr(namespace, self.dest, items)

class _ExtendConstAction(_AppendConstAction):
def __call__(self, parser, namespace, values, option_string=None):
items = getattr(namespace, self.dest, None)
items = _copy_items(items)
items.extend(self.const)
setattr(namespace, self.dest, items)

# ==============
# Type classes
# ==============
Expand Down Expand Up @@ -1328,6 +1336,7 @@ def __init__(self,
self.register('action', 'version', _VersionAction)
self.register('action', 'parsers', _SubParsersAction)
self.register('action', 'extend', _ExtendAction)
self.register('action', 'extend_const', _ExtendConstAction)

# raise an exception if the conflict handler is invalid
self._get_handler()
Expand Down
28 changes: 28 additions & 0 deletions Lib/test/test_argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -774,6 +774,34 @@ class TestOptionalsActionAppendConstWithDefault(ParserTestCase):
('-b -cx -b -cyz', NS(b=['X', Exception, 'x', Exception, 'yz'])),
]

class TestOptionalsActionExtendConst(ParserTestCase):
"""Tests the extend_const action for an Optional"""

argument_signatures = [
Sig('-b', action='extend_const', const=[Exception, Exception]),
Sig('-c', action='extend', dest='b'),
]
failures = ['a', '-c', 'a -c', '-bx', '-b x']
successes = [
('', NS(b=None)),
('-b', NS(b=[Exception, Exception])),
('-b -cx -b -cyz', NS(b=[Exception, Exception, 'x', Exception, Exception, 'y', 'z'])),
]

class TestOptionalsActionExtendConstWithDefault(ParserTestCase):
"""Tests the extend_const action for an Optional"""

argument_signatures = [
Sig('-b', action='extend_const', const=[Exception, Exception], default=['X']),
Sig('-c', action='extend', dest='b'),
]
failures = ['a', '-c', 'a -c', '-bx', '-b x']
successes = [
('', NS(b=['X'])),
('-b', NS(b=['X', Exception, Exception])),
('-b -cx -b -cyz', NS(b=['X', Exception, Exception, 'x', Exception, Exception, 'y', 'z'])),
]


class TestOptionalsActionCount(ParserTestCase):
"""Tests the count action for an Optional"""
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add ``extend_const`` action to argparse.