Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional argparse with choice option

Below are three arguments I am writing in a module.

parser.add_argument('--Type',type=str,choices=['a','b','c'],help='Options include: a,b,c.',required=True)

parser.add_argument('--Input',default=False,help='Generate input files',required=False)

parser.add_argument('--Directory',default=False,help='Secondary directory',required='--Input' in sys.argv)

The --Type is possible with three options: a,b,c.

Currently, I have it set up so that, if --Directory is true, it requires --Input to be true.

However, I would like add an additional condition to --Directory to require --Type to be == 'c'.

How do I alter the required option in the --Directory argument so that it needs both --Input and --Type == 'c'?

like image 259
Andrew Hamel Avatar asked Sep 14 '25 06:09

Andrew Hamel


2 Answers

Decouple argument parsing from your requirements.

parser.add_argument('--Type', choices=['a','b','c'], required=True)
parser.add_argument('--Input', action='store_true')
parser.add_argument('--Directory', action='store_true')

args = parser.parse_args()

if args.Directory and args.Type != 'c' and not args.input:
    raise argparse.ArgumentError("--Directory requires --Type c and --Input")

(Note that action='store_true' automatically sets type=bool and default=False.)

like image 117
chepner Avatar answered Sep 15 '25 19:09

chepner


I would not use the required parameter for either of those things, it is kind of error-prone and not very readable. Just check the validity of the arguments after parsing.

import argparse

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--Type', type=str, choices=['a','b','c'], help='Options include: a,b,c.', required=True)
    parser.add_argument('--Input', default=False, help='Generate input files', required=False)
    parser.add_argument('--Directory', default=False, help='Secondary directory', required=False)
    parsed_args = parser.parse_args()
    if parsed_args.Directory and not (parsed_args.Input and parsed_args.Type == 'c'):
        parser.error('option --Directory requires --Input and --Type c.')
like image 45
jdehesa Avatar answered Sep 15 '25 19:09

jdehesa