is it possible to extend subparsers new names without implementing all of their parameters twice?
I have a program, let's call it pgmm
which has a sub function create
. This create function needs a config file somewhere. To prevent looking for this, create can have the option --noconfig
.
What I want now is to have some 'pseudo sub parser' maybe like init
, which is basically the same as create --noconfig
I hope that there is a way without implementing the same twice..
is it?
I don't know of a way of adding this logic to argparse
per se, but you don't have to do that to get the behavior you want. You can create a subparser for create
and add init
as an alias for that command so that either command name can be used. Then, when you consume the arguments after calling parse_args
, check which subcommand was executed, and if it was init
, then force the noconfig
flag to True
:
sub_parsers = parser.add_subparsers(dest="action")
...
sub = sub_parsers.add_parser('create', aliases=['init'])
sub.add_argument('--noconfig', action='store_true')
....
args = parser.parse_args(args)
if args.action == 'init':
args.noconfig = True