Search code examples
pythonexceptioncommand-line-argumentsargparseoptional-arguments

Optional Arguments in Argparse


How can I generate an error message if fewer than required optional arguments are passed in the command line while using argparse in code? for example, I have 5 optional arguments and I want to generate an error message if fewer than 4 optional arguments are used at any time. My beginner brain can't figure this out.

import argparse
import math
parser = argparse.ArgumentParser(description='Loan Calculator')
parser.add_argument('--type', type=str)
parser.add_argument('--principal', type=int)
parser.add_argument('--periods', type=int)
parser.add_argument('--interest', type=float)
parser.add_argument('--payment', type=int)
args = parser.parse_args()

Solution

  • This is something that's most simply handled after you've called parse_args. Count how many of the options still have the default value of None. If there's more than 1, raise an error.

    args = parser.parse_args()
    if 1 < sum(1 for x in [args.type, args.principal, args.periods, args.interest, args.payment] if x is None):
        sys.exit("Too few options specified")