I'm subclassing ArgumentParser so that I can DRY up the common code I have across multiple commands in my package. However, I'm running into some weird behaviour which I'm not able to explain.
See this very simplified version of my program and note the two lines with comments at the end:
class Parser(argparse.ArgumentParser):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self._add_common_args() # (1)
def _add_common_args(self):
self.add_argument('-s', '--stage', required=True, type=str.lower)
def parse(self):
return self.parse_args(['--stage', 'alpha', 'list-services'])
parser = Parser(prog='my_prog')
# parser._add_common_args() # (2)
subparsers = parser.add_subparsers(dest='resource')
subparsers.required = True
services_parser = subparsers.add_parser('list-services')
parser.parse()
If I run this, the program returns
usage: my_prog list-services [-h] -s STAGE
my_prog list-services: error: the following arguments are required: -s/--stage
But, if I comment out the line at (1) and uncomment the line at (2), it works as expected.
What's going on here?