Argparse set_defaults for sub-parsers broken beyond Python 2.7.6? -
i have application using argparse broken latest versions of python. no longer able alter defaults sub-commands.
my app has various modules , optional gui. gui calls modules via sub-commands, , there ini file may alter argument defaults.
the gui has created parser , sub-parsers, passing arguments set gui user. options in ini file may override defaults in sub-parsers.
this works in 2.7.6, broken later releases due apparent change in argparse.
import argparse # create top-level parser parser = argparse.argumentparser(prog='prog') parser.add_argument('--foo', action='store_true', dest='_foo') subparsers = parser.add_subparsers(help='sub-command help') # create parser "a" command parser_a = subparsers.add_parser('a', help='a help') parser_a.add_argument('--bar', type=int, default=0, dest='_bar') #use ini file alter default d_ini = {'_bar': '1'} parser.set_defaults(**d_ini) # parse argument lists print parser.parse_args(['a'])
in python 2.7.6 prints expected:
namespace(_bar=1, _foo=false)
but in later releases, eg. 2.7.10 prints
namespace(_bar=0, _foo=false)
am using argparse incorrectly, because if python bug has persisted few releases now?
do need process ini file before adding sub-parser defaults? more cumbersome current approach need done separately each argument, , there many. python documentation argumentparser.set_defaults explicitly states "parser-level defaults can particularly useful when working multiple parsers", surprising if facility has been compromised.
in case, parser defaults must applied sub parser of interest. is, in code above, should have:
# set defaults on parser_a parser_a.set_defaults(**d_ini)
setting defaults on parser
not set defaults on sub parsers. instead sets default values top level (global) arguments. why? way possible program take option --bar
, , multiple subcommands a
, b
, c
take option --bar
different defaults.
the former behaviour, in 2.7.6, appears in 3.3, should considered bug.
Comments
Post a Comment