I tested a solution using mutually_exclusive_group . The idea is to define a group that includes --arg twice. The parser maintains a list of seen_non_default_actions and checks for conflicts with an exclusive group before taking action on a new line of the argument. If --arg already on this list, the next call will conflict with it and cause an error.
There are several problems with this approach.
1) existing actions cannot be added to the new group mutually-excluding_groups. At fooobar.com/questions/797096 / ... I illustrate a scrap that circumvents this. He also refers to the proposed patch, which makes this easier.
2) currently parse_args adds the action to the list seen_non_default_actions , and then checks for conflicts. This means that the first --arg will conflict with itself. The solution is to switch the order. Check for conflicts first, then add the action to the list.
import my_argparse as argparse
When called with various arguments, it creates:
$ python3 test.py -h usage: PROG [-h] [--arg ARG | --arg ARG] optional arguments: -h, --help show this help message and exit --arg ARG use this argument only once $ python3 test.py --arg test Namespace(arg='test') $ python3 test.py --arg test --arg next usage: PROG [-h] [--arg ARG | --arg ARG] PROG: error: argument --arg: not allowed with argument --arg
I am surprised, although this is an intuitive way of saying, "Use this argument only once." Does the use string use [--arg ARG | --arg ARG] [--arg ARG | --arg ARG] is this? And is the argument --arg: not allowed with argument --arg error message argument --arg: not allowed with argument --arg ?
source share