I have a CLI I'm building which utilizes subparsers for sub-commands similar to tools like git. Some of my sub-commands share common options so I have a group parser that defines the options, and each sub-command that needs them uses parents=group_parser
as one of the arguments. For example:
group_parser = argparse.ArgumentParser()
group_parser.add_argument('-f', '--foo', action='store_true')
command1_parser = subparsers.add_parser('command1', parents=[group_parser])
command2_parser = subparsers.add_parser('command2', parents=[group_parser])
So as you see both command1 and command2 inherit the option --foo
. What I'm trying to do is update the helptext for foo separately on command1 and command2. For instance if I run myprog command1 -h
, I want it to say a different help message for --foo
that when I run myprog command2 -h
. The problem is until I do parse_args()
there isn't a namespace to update for that argument, so something like this doesn't work:
group_parser = argparse.ArgumentParser()
group_parser.add_argument('-f', '--foo', action='store_true')
command1_parser = subparsers.add_parser('command1', parents=[group_parser])
command1.foo['help'] = "foo help for command1"
command2_parser = subparsers.add_parser('command2', parents=[group_parser])
command2.foo['help'] = "foo help for command2"
Is this possible to somehow add additional parameters to an argument outside of the add_argument()
function? The only other solution is to not use the inherited parent and just define foo separately for each sub-command, but if there's a way to update parameters, that would be ideal.