1

I have two parameters that I need either both or neither of. I thought of two solutions: one optional parameter with nargs=2, or two optional parameters that are contingent on each other. I found answers for nargs=2, but the help output seems messy and opaque to users. I'd like to investigate making two optional parameters that are contingent on each other.

If I provide the environment, I also need to provide the service, and vice-versa. If I provide neither, that's fine.

Normal optional parameters get added with this type of help output:

usage: script.py [-h] [-e ENVIRONMENT] [-s SERVICE] [-u] [-d]

I want this type of help output (and the underlying requirements):

usage: script.py [-h] [-e ENVIRONMENT -s SERVICE] [-u] [-d]

Is there a flag or easy way to do this, so it shows up clearly in the help? Writing an additional check to enforce this is trivial, but making my help clear to users seems out of my reach.

In the mean time, I've added help to the argparse like this: parser.add_argument('-s', '--service', metavar='SERVICE', help='Service to use, if -e also used')

Beweeted
  • 319
  • 2
  • 7

1 Answers1

1

Though this option is not currently supported in argparse, you can use subparser as a workaround solution. Each dependent parameter will define a new subparser which will contain the other parameter as a required parameter. It's a bit ugly and will create some code duplication, but it will solve your dependency problem and also will be reflected properly in the help and error.

NirO
  • 216
  • 2
  • 12