Repository navigation
Open
Labels
stdlibStandard Library Python modules in the Lib/ directorytype-featureA feature request or enhancement
Description
| BPO | 11588 |
|---|---|
| Nosy | @cjmayo, @ikelos, @IIIIllllIIIIllllIIIIllllIIIIllllIIIIll, @iforapsy |
| Files |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
assignee = None
closed_at = None
created_at = <Date 2011-03-17.15:51:29.761>
labels = ['type-feature']
title = 'Add "necessarily inclusive" groups to argparse'
updated_at = <Date 2019-11-07.02:24:58.703>
user = 'https://bugs.python.org/JohnDidion'bugs.python.org fields:
activity = <Date 2019-11-07.02:24:58.703>
actor = 'iforapsy'
assignee = 'none'
closed = False
closed_date = None
closer = None
components = []
creation = <Date 2011-03-17.15:51:29.761>
creator = 'John.Didion'
dependencies = []
files = ['34176', '34193', '34285', '35608', '36553']
hgrepos = []
issue_num = 11588
keywords = ['patch']
message_count = 17.0
messages = ['131262', '132241', '134560', '211240', '211261', '211878', '211947', '212228', '212243', '212733', '215777', '220419', '226324', '226469', '265734', '286582', '294569']
nosy_count = 9.0
nosy_names = ['bethard', 'cjmayo', 'ikelos', 'xuanji', 'John.Didion', 'manveru', 'paul.j3', 'pgacv2', 'iforapsy']
pr_nums = []
priority = 'normal'
resolution = None
stage = 'needs patch'
status = 'open'
superseder = None
type = 'enhancement'
url = 'https://bugs.python.org/issue11588'
versions = ['Python 3.3']Linked PRs
Reacted by Liu Yihua, Anton Dyshkant, William, FrantaM, Dimitris Theodorou, Frieder Schrempf, Nic De Muyer, Bar Harel, Snawe, Fredrik Roubert and 50 more
Metadata
Metadata
Assignees
Labels
stdlibStandard Library Python modules in the Lib/ directorytype-featureA feature request or enhancement
Projects
- StatusShow more project fieldsFeatures
Activity
JohnDidion commentedon Mar 17, 2011
Just as some options are mutually exclusive, there are others that are "necessarily inclusive," i.e. all or nothing. I propose the addition of ArgumentParser.add_necessarily_inclusive_group(required=True).
This also means that argparse will need to support nested groups. For example, if I want to set up options such that the user has to provide an output file OR (an output directory AND (an output file pattern OR an output file extension)):
The usage should then look like:
(-o FILE | (-O DIR & (-p PATTERN | -s SUFFIX))
bethard commentedon Mar 26, 2011
I think this is a great suggestion. Care to work on a patch?
manveru commentedon Apr 27, 2011
I am subscribing to this idea as I've just fall into such use case where I need it. I would like to submit a patch, but I still have difficulties to understand argparse code not much spare time to spent on this.
paulj3 commentedon Feb 14, 2014
The suggestion in this issue is to add a 'mutually_inclusive_group' mechanism, one that would let users specify that certain sets of arguments must occur together. Furthermore there was mention of allowing some sort of nesting.
Modeling it on the mutually_exclusive_group would be straight forward. But should it affect the usage and help display?mutually_exclusive_groups add a messy layer to the usage formatting.
The only place such a group would act would be at the end of '_parse_known_args', where the current code checks for things like required actions (and mxgroups). A test at this point could use 'namespace', 'seen_actions' and 'seen_non_default_actions' to check whether the required group actions were seen.
But the only thing that the argument_group contributes to this test is a list of argument names ('dest'?). Why not provide this list directly? And what if the user wants A to occur together with either B or C, but not both? Or make the inclusivity conditional on the value of A?
Currently users can define argument interactions in a couple of ways. They can define custom Actions. In test_argparse.py there's a custom Actions test that does something like this (using '--spam' and 'badger'). But tests in Actions depend on the order in which arguments are given.
An alternative is to test for interactions of arguments after
parse_args. However the only information that the user has at this point is the args namespace. Reliably distinguishing between non-occurrence of arguments and default values can be difficult.I am proposing 'cross_test' mechanism that would give the user access to the 'seen_actions' and 'seen_non_default_actions' sets that 'mutually_exclusive_groups' use. Specifically an optional function can be called at the end of '_parse_known_args' that has access to these sets as well as the parser and the namespace.
The core of the change would be adding
at the end of 'parser._parse_known_args'. In addition 'cross_test' (or some other name) could be added to the 'ArgumentParser.__init__' arguments.
The feature could be used by defining such a 'cross_test' function and adding it to the parser (either instance or subclass)
The patch proposed http://bugs.python.org/issue18943 should be included
with any changes here since it refines the setting of 'seen_non_default_actions'.
I am working on tests and examples of such functionality.
paulj3 commentedon Feb 15, 2014
Regarding a usage line like:
The simplest option is to just a custom written 'usage' parameter.
With the existing HelpFormatter, a nested grouping like this is next to impossible. It formats the arguments (e.g.'-O DIR'), interleaves the group symbols, and then trims out the excess spaces and symbols.
http://bugs.python.org/issue10984 is a request to allow overlapping mutually_exclusive_groups. It loops on the groups, formatting each. It would be easier with that to format several different types of groups, and to handle nested ones.
What would it take to convert a usage string like that into a logical expression that tests for the proper occurrence (or non-occurrence) of the various arguments. It might, for example be converted to
where 'exc' and 'inc' are exclusive and inclusive tests, and 'file','dir' etc are booleans. And what would be the error message(s) if this expression fails?
I can imagine a factory function that would take usage line (or other expression of groupings), and produce a function that would implement a cross_test (as outlined in my previous post). It would be, in effect, a micro-language compiler.
paulj3 commentedon Feb 21, 2014
This patch uses:
to get a list of functions to run at the end of '_parse_known_args'.
I replaced all of the mutually_exclusive_group tests (3 places) in the ArgumentParser with a static function defined in class _MutuallyExclusiveGroup, and registered this function. This refactoring should make it easier to add other specialized groups (e.g. inclusive) in the future.
I'm using the _registries because they are already being shared among groups.
A user can also register a custom testing function. For example:
This patched 'argparse.py' runs 'test_argparse.py' without error.
This patch does not include the bpo-18943 changes, which make setting 'seen_non_default_actions' more reliable.
paulj3 commentedon Feb 22, 2014
This is an example of using 'patch_w_mxg2.diff' to handle the inclusive group case proposed by the OP.
Since 'seen_non_default_actions' (and 'seen_actions') is a set of 'Actions', it is convenient to use 'set' methods with pointers to the actions that a collected during setup. Tests could also be done with the 'dest' or other action attributes.
In this example I wrote 3 simple tests corresponding to the 3 proposed groups, but they could also have been written as one test.
In theory tests like this could be generated from groups as proposed by the OP. There is one case in 'test_argparse.py' where a mutually_exclusive_group is nested in an argument_group. But the current groups do not implement nesting. A (plain) argument_group does not share its '_group_actions' list with its 'container'. A mutually_exclusive_group shares its '_group_actions' but the result is a flat list (no nesting).
For now I think it is more useful to give users tools to write custom 'cross_tests' than to generalize the 'group' classes.
paulj3 commentedon Feb 25, 2014
http://stackoverflow.com/questions/11455218
python, argparse: enable input parameter when another one has been specified
$ python myScript.py --parameter1 value1 $ python myScript.py --parameter1 value1 --parameter2 value2 $ python myScript.py --parameter2 value2 # errorThis is an example where a 'mutually inclusive group' wouldn't quite do the job.
The proposed answers mostly use a custom Action. I'd lean toward an after-the-parse test of the namespace.
With the patch I proposed this could be implemented with:
One poster on that thread claimed that the use of 'a1 = parser.add_argument...' is using an undocumented feature. The fact that
add_argumentreturns anactionobject, should be illustrated in the documentation, and may be explicitly noted. I'll have to review the documentation to see if this is the case.paulj3 commentedon Feb 26, 2014
The addition of a simple decorator to the 'ArgumentParser' class, would simplify registering the tests:
which would be used as:
paulj3 commentedon Mar 4, 2014
A couple more thoughts on an expanded argument testing mechanism:
'seen_actions' is used only to test whether all required actions have been seen. These 2 sets differ in how positionals with '?*' are categorized. Positionals like this are always 'seen', even if they just get the default value. But they are not required (the case of a '*' positional without default needs to be revisited.)
If 'seen_non_default_actions' is changed to a list (currently its a set), users could test for repeated use on an optional, or even the order of arguments.
One way to make this testing mechanism more user-friendly is to provide convenience functions via a decorator.
For example the decorator could wrap the 'seen_non_default_actions' argument in a 'seen' function. Such a function could accept either an Action or a 'dest' string, it could accept a single Action, or a list of them, etc. There could be other functions like 'count', 'unique', 'mutually_exclusive', 'inclusive', etc.
The attached script experiments with several versions of decorators. Some sort of testing Class is probably the way to go if we want to provide many convenience methods.
paulj3 commentedon Apr 8, 2014
http://stackoverflow.com/questions/22929087
A question that could be addressed with this patch(es)
In a subparser:
The
gcase does not fit either the inclusive or exclusive group patterns.paulj3 commentedon Jun 13, 2014
I have developed a UsageGroup class that can implement nested 'inclusive' tests. Using this, the original example in this issue could be coded as 3 groups, 2 mutually_exclusive and inclusive one.
UsageGroup is like MutuallyExclusiveGroup, except that:
A nested group is added to self._group_actions, but its actions are not. Those actions are added separately to the parser._actions list. Thus the '_group_actions' list can be a mix of actions and groups.
Each group has a 'testfn', a function that tests its own '_group_actions' against the 'seen_non_default_actions' provided by the parser. These are similar to the 'cross_test' functions I developed
earlier. The 'testfn' for primary level usage groups are registered with cross_tests (here renamed 'usage_tests')). 'testfn' for nested groups are handled recursively in the containing testfn.
Normally 'testfn' is chosen based on 'kind' and 'required' parameters. 'kind' can implement logical actions like 'xor' (mutually exclusive), 'and' (inclusive), 'or' (any), 'not'. These seem to cover most possibilities, though custom tests are possible.
Each group has several variables defining how it is to be formatted. The basic ones are 'joiner' (e.g. '|&^,') and 'parens' (e.g. (),[],{}). Or a totally custom 'usage' string could be used.
The Usage Formatter is a derivative of the MultiGroupHelpFormatter I wrote for bpo-10984. Each group is formatted individually (and possibly recursively).
Existing actions and usage groups can be added to a usage group. This adds to the flexibility of the usage testing, though the formatted usage line could easily become unwieldy.
A 'mxg' UsageGroup effectively replaces a MutuallyExclusiveGroup.
self._add_container_actions(parent) knows nothing about this class yet.
The attached 'usagegroup.py' file has the core code for this change. The full working code is at
It incorporates too many other changes (from other bug issues) to post
here as a simple patch file (yet). I have a number of test scripts, but haven't cast those as unittests. Same goes for documentation.
paulj3 commentedon Sep 3, 2014
http://stackoverflow.com/questions/25626109/python-argparse-conditionally-required-arguments
asks about implementing a 'conditionally-required-arguments' case in
argparse. The post-parsing test is simple enough:I believe the clearest and shortest expression using Groups is:
The usage is (using !() to mark a 'nand' test):
This uses a 'nand' group, with a 'not-all' test (False if all its actions are present, True otherwise).
paulj3 commentedon Sep 6, 2014
Attached is a patch for 3.5.0 dev that adds UsageGroups. Now different 'kinds' are implemented as subclasses, which are accessed via the registry:
Open issues:
23 remaining items
cuppajoeman commentedon Apr 27, 2024
I would also appreciate this feature, doing it manually for now.
haytechy commentedon Oct 18, 2024
Would also love this feature <3
Arcitec commentedon Nov 29, 2024
Doing it manually like this for now:
barakbd commentedon Jan 3, 2025
+1
RobinSobczyk commentedon Jan 16, 2025
+1, ability to create necessarily inclusive groups and manage nested groups would be incredible
johnbertrand commentedon Feb 19, 2025
I just came here looking for this feature. +1. Thank you
savannahostrowski commentedon Mar 3, 2025
Given that nesting argument groups/mutually exclusive groups is being removed in 3.14(deprecated since 3.11), I'd be curious to know how valuable this feature is now. The checks for necessarily inclusive arguments should be fairly straightforward in a flat group, right?
picnixz commentedon Mar 4, 2025
It's usually straightforward but it adds some lines that I sometimes find bothersome to write. For instance, the error message is not standardized in one place, and it's sometimes harder to maintain ourselves:
It also doesn't read easily. Maybe we could have some recipe/suggest some PyPI package instead? I still think that nested argument groups are relevant but I won't be against the deprecation that has already been planned for 3 versions (somehow, I would think that mutually exclusive groups of necessarily inclusive groups would be awesome but we can also live with subparsers which are usually cleaner, although the
--helpoutput would itself be "nested")electric-coder commentedon Mar 31, 2025
argparse is about giving quality-of-life niceties to the programmer, including automating the usage and the help as far as possible. By not including boolean niceties you either cripple argparse to limited usability or defeat its purpose. Either way it's a 14 yo issue and I'm, in fact, still not sure exactly what's being deprecated? Is it
add_mutually_exclusive_group()as a method, is the deprecation a specific use of the method? No one knows, and neither is it evident from the notice in the docs or from these GH threads what the status quo or the way forward will be. - But dare I say there's a use for boolean argparse ops and ontological groupings? After 14 years and +100 votes that much should be evident!savannahostrowski commentedon Jun 5, 2026
Before I dive into next steps, a quick note: being hostile toward maintainers for asking clarifying questions doesn't move things forward. If anything, it does the opposite. There's clearly been a lot of interest over the years, and that's great, but this is open source: anyone is free to propose, discuss, and offer help, and a constructive tone is what gets things done.
That said, I do hear the demand. This is one of the most requested argparse features and I want to find a way to move it forward.
First, to clear things up:
add_mutually_exclusive_group()is not going away. What was deprecated (3.11) and removed (3.14, #127133) is nesting groups inside other groups.That distinction matters here, because the requests in this thread really fall into three shapes:
--username/--password).--proxis given, then--lportand--rportare required," but--lporton its own is fine.(-o | (-O & (-p | -s))).(3) depends on the nesting that was just removed, and I don't intend to reintroduce it at this time. (2) is a genuinely different relationship that a symmetric group can't express. IMO, it's better handled by validating after
parse_args(), or possibly a separate feature if there's demand. Users who need full boolean logic over arguments are also well served by a richer CLI library on PyPI.(1), though, is a clean and common pattern that I think is worth adding on its own so that's what I've scoped a draft PR to: #150981
If your use case is really (2) rather than (1), please say so here. It helps me gauge whether the symmetric group is the right primitive or whether something more general is warranted.
roubert commentedon Jun 6, 2026
It's great to see things moving here and I'm sure the
add_mutually_inclusive_group()feature will be useful to many, but unfortunately for myself the kind of functionality I'd need to be able to simplify my code would be your option 3.It would, of course, be possible for me to use some third party library instead, but it has some serious advantages for maintainability to be able to use functionality from the standard library and I currently get by with just two subsequent calls to
parse_args()in order to sort out "if-Awas given then either-Bor-Cmust also be given", which is a level at which it'd be very nice if the standard library were able to make this easier, but not worth it to introduce a third party library.electric-coder commentedon Jul 1, 2026
Not meant to be hostile, but I did loose 1 month of my life trying to figure out how to get stdlib's argparse to work (for options 1. and 2. so not complex like option 3.) after I had committed to using it, precisely because of the bugs we're discussing here (the pydocs promise more than they deliver). My conclusion after the loss of health this caused me (and here please notice: this is not meant as sarcasm, but an assertion I regret having to make) is that I have to advise the average dev to go straight for a 3rd party library if their argparse needs something more complex than the bare minimum.
Considering how commonplace argparse is and how easily the module can become a pitfall I'd urge the PSF to either invest in developing the module or put a carefully worded disclaimer on top of the module's long documentation clearly advising when it's better to choose a 3rd party library. Something like the 3 point list you just developed @savannahostrowski because the status quo is just too taxing IMO.
vergenzt commentedon Jul 2, 2026
?
?
I genuinely don't understand what the complexity here is? I don't see the lack of this feature as making anything impossible, just ever so slightly less convenient. Why couldn't either of those requirements if yours simply be done with a few lines in userland after arg parsing?
To me this is a nice-to-have. And it would be nice to have! But I'm not gonna lose sleep over it. 🤷🏻