Define arguments like `(N | name [name ...])` with argparse

I’ve tried to write a script that either accepts a number of objects as argument, or accepts names (not beginning with digit) of objects.

I know that’s a little beyond argparse's ability, as it won’t know if xxx.py 1 should belong to which pattern. So I basically uses nargs='+' for the name argument and do the dispatch myself, but still hopes to show command line hint as (N | name [name ...]) rather than just name [name ...].

Would it be possible with argparse?

I think you would rewrite the help text yourself. For example:

import argparse

parser = argparse.ArgumentParser(
  prog="my-sweet-script",
  usage="%(prog)s (N | name [name ...])",
  description="Process objects. If given a number, process this many objects."
)

parser.add_argument(
  "number_or_names",
  nargs="+",
  help=argparse.SUPPRESS,
)

parser.print_help()

printing:

usage: my-sweet-script (N | name [name ...])

Process objects. If given a number, process this many objects.

optional arguments:
  -h, --help  show this help message and exit

Of course, you can also keep the argument description under the positional arguments section using metavar:

import argparse

parser = argparse.ArgumentParser(
  prog="my-sweet-script",
  usage="%(prog)s (N | name [name ...])",
)

parser.add_argument(
  "number_or_names",
  nargs="+",
  metavar="(N | name [name ...])",
  help="Objects to process. Can be a number, to process this many objects."
)

parser.print_help()

The latter version outputs:

usage: my-sweet-script (N | name [name ...])

positional arguments:
  (N | name [name ...])
                        Objects to process. Can be a number, to process this
                        many objects.

optional arguments:
  -h, --help            show this help message and exit

Thank you for the suggestion. It’s a nice idea to totally suppress the usage description when there’s only that argument. In fact the script accepts some options, so manually assigning an usage string that contains all the options would be a little painful. It seems that the best way is to extend HelpFormatter and override _format_usage.