Author roganartu
Recipients rhettinger, roganartu
Date 2021-02-08.04:12:31
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1612757551.9.0.453042152988.issue43160@roundup.psfhosted.org>
In-reply-to
Content
I submitted this to the python-ideas mailing list early last year: https://mail.python.org/archives/list/python-ideas@python.org/thread/7ZHY7HFFQHIX3YWWCIJTNB4DRG2NQDOV/. Recently I had some time to implement it (it actually turned out to be pretty trivial), so thought I'd put forward a PR.

Here's the summary from the mailing list submission:

I have found myself a few times in a position where I have a repeated argument that uses the append action, along with some convenience arguments that append a specific const to that same dest (eg:  --filter-x being made equivalent to --filter x via append_const). This is particularly useful in cli apps that expose some kind of powerful-but-verbose filtering capability, while also providing shorter aliases for common invocations. I'm sure there are other use cases, but this is the one I'm most familiar with.

The natural extension to this filtering idea are convenience args that set two const values (eg: --filter x --filter y being equivalent to --filter-x-y), but there is no extend_const action to enable this.

While this is possible (and rather straight forward) to add via a custom action, I feel like this should be a built-in action instead. append has append_const, it seems intuitive and reasonable to expect extend to have extend_const too (my anecdotal experience the first time I came across this need was that I simply tried using extend_const without checking the docs, assuming it already existed).

Here's an excerpt from the docs I drafted for this addition that hopefully convey the intent and use case clearly.

+* ``'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'>])
History
Date User Action Args
2021-02-08 04:12:31roganartusetrecipients: + roganartu, rhettinger
2021-02-08 04:12:31roganartusetmessageid: <1612757551.9.0.453042152988.issue43160@roundup.psfhosted.org>
2021-02-08 04:12:31roganartulinkissue43160 messages
2021-02-08 04:12:31roganartucreate