I wanted this once, and found that argparse
doesn't support it natively, so I wrote it like this.
#!/usr/bin/env python
import argparse as ap
parser = ap.ArgumentParser(usage='%(prog)s [-h] [a b]\n')
parser.add_argument('ab',
nargs='*',
help='specify 2 or 0 items',
default=['a', 'b'])
args = parser.parse_args()
if len(args.ab) != 2:
parser.error('expected 2 arguments')
print(args.ab)
Note over-riding the usage message when you create the parser, because the default usage message will be misleading otherwise.