0

I am trying to achieve something like this:

python main.py --severity high --start_date 10/12/2016

python main.py --name samuel

Here, the argument --start_date arg will only be valid if previous argument is --severity. If we have --name instead of --severity. The argparse should return error. How do I achieve this? I have looked for a while and couldn't find something that I wanted to do.

Community
  • 1
  • 1
paris_serviola
  • 361
  • 1
  • 6
  • 19
  • What would you do if they gave `--severity` after `--start_date`? Or `--name` along with `--severity`? `argparse` allows you to enter flagged arguments like this in any order. If order is important to you, then `argparse` is the wrong tool. – hpaulj Jan 04 '17 at 23:04
  • A `mutually_exclusve_group` can raise an error if `--start_date` is provided along with `--name`, but there isn't a mechanism for `mutually-inclusive` testing. – hpaulj Jan 05 '17 at 00:46
  • A useful prior question: http://stackoverflow.com/questions/19414060/argparse-required-argument-y-if-x-is-present – hpaulj Jan 05 '17 at 00:48
  • @hpauulj severity should always come before start_date. – paris_serviola Jan 05 '17 at 07:05
  • 1
    The only way to enforce that with `argparse` is to construct one or more custom `Action` classes. As an exercise I could probably do that, but I wouldn't recommend it for production code. – hpaulj Jan 05 '17 at 08:27

1 Answers1

1

Unfortunately, argparse does not have such capability, so you will have to do it explicitly. Something like this should work:

...
args = parser.parse_args()
if getattr(args, 'start_date', None) and not getattr(args, 'severity', None):
    parser.print_help()
    parser.exit(1, "error message")
Marat
  • 15,215
  • 2
  • 39
  • 48
  • Unless you used `default=SUPPRESS` the namespace will always have a `severity` attribute. `args.severity is None` is a better test. – hpaulj Jan 05 '17 at 00:24
  • @hpaulj good catch! changed to getattr with default value to make it work in both cases. Though, `if args.start_date and not args.severity:` will be more readable – Marat Jan 05 '17 at 03:22