serhiy-storchaka · GitHub

Bug report

argparse supports grouping mutually exclusive arguments in the usage. For example:

import argparse
parser = argparse.ArgumentParser(prog="PROG")
group = parser.add_mutually_exclusive_group()
group.add_argument('-f', action='store_true')
group.add_argument('x', nargs='?')
print(parser.format_usage())

Output:

usage: PROG [-h] [-f | x]

But it does not work if there is a positional argument before a mutually exclusive group containing positional argument:

import argparse
parser = argparse.ArgumentParser(prog="PROG")
parser.add_argument('x')
group = parser.add_mutually_exclusive_group()
group.add_argument('-f', action='store_true')
group.add_argument('y', nargs='?')
print(parser.format_usage())

Output:

usage: PROG [-h] [-f] x [y]

Expected output:

usage: PROG [-h] x [-f | y]

Or there is an optional argument after a mutually exclusive group:

import argparse
parser = argparse.ArgumentParser(prog="PROG")
group = parser.add_mutually_exclusive_group()
group.add_argument('-f', action='store_true')
group.add_argument('x', nargs='?')
parser.add_argument('-g', action='store_true')
print(parser.format_usage())

Output:

usage: PROG [-h] [-f] [-g] [x]

Expected output:

usage: PROG [-h] [-f | x] [-g]

Or there are multiple mutually exclusive groups:

import argparse
parser = argparse.ArgumentParser(prog="PROG")
group1 = parser.add_mutually_exclusive_group()
group1.add_argument('-f', action='store_true')
group1.add_argument('x', nargs='?')
group2 = parser.add_mutually_exclusive_group()
group2.add_argument('-g', action='store_true')
group2.add_argument('y', nargs='?')
print(parser.format_usage())

Output:

usage: PROG [-h] [-f] [-g] [x] [y]

Expected output:

usage: PROG [-h] [-f | x] [-g | y]

(or something like).

Linked PRs

Read the original on github.com ↗