Are there best practices or style guidelines for working with Python's argparse
module?
I work with argparse
on a regular basis, and it quickly takes up a respectable number of lines to handle all the configuration. For almost everything I find that sticking close to PEP 8 results in clean, readable code, but not here. The end result is always an ugly block of code that is painful to read.
Painful to read is not Pythonic:
So is there a PEP or some other resource that provides guidelines for how to better format this code?
A sample of the ugliness (mostly following PEP 8):
parser = argparse.ArgumentParser(description='A nontrivial modular command')
subparsers = parser.add_subparsers(help='sub-command help')
parser_load = subparsers.add_parser('load', help='Load something somewhere')
parser_load.add_argument('--config',
help='Path to configuration file for special settings')
parser_load.add_argument('--dir', default=os.getcwd(),
help='The directory to load')
parser_load.add_argument('book', help='The book to load into this big thing')
parser_load.add_argument('chapter', nargs='?', default='',
help='Optionally specify a chapter')
parser_load.add_argument('verse', nargs='*',
help='Optionally pick as many verses as you want to'
' load')
parser_load.set_defaults(command='load')
parser_write = subparsers.add_parser(
'write', help='Execute commands defined in a config file')
parser_write.add_argument('config', help='The path to the config file')
parser_write.set_defaults(command='write')
parser_save = subparsers.add_parser(
'save',
help='Save this big thing for use somewhere later')
parser_save.add_argument('-n', '--name', default=None,
help='The name of the component to save')
parser_save.add_argument('path', help="The way out of Plato's cave")
parser_save.set_defaults(command='save')
...
args = parser.parse_args()
click
: click.pocoo.org/5, much nicer arguments via decorators – Narcoseparser_X
/parser_Y
toX_parser
/Y_parser
so that not every line begins withparser
andX
/Y
can be distinguished more easily. – Rosenthalrequired=False
in lieu ofnargs='?'
. If required is false, the value is none if it's not specified, and it makes my code easier to read because I know thatnargs
means "get ready to do something with a list". – Delossantosrequired
is not allowed as a parameter for a positional (try it). It automatically sets therequired
attribute based onnargs
.required=True
may be useful for a optional (a 'required optional'?).nargs='?'
is most useful when used along with aconst
anddefault
parameter (also optionals). – Panay--
. Maybe @Rosenthal was on to something :) I usually use comments to separate parsers as well, with positional arguments at the top. FWIW, in Go, I'll use spf13/cobra and have those subparsers in their own functions - much more intuitive. – Delossantos