Python argparse type and choice restrictions with nargs > 1

Side note, because this question turns up when searching for "argparse nargs choices":

A custom action is only needed if the nargs arguments require a heterogenous type validation, i.e., the argument at index 0 should be a different type (here: limited type of subjects) than the argument at index 1 (here: float) etc.

If a homogenous type validation is desired, it is sufficient to combine nargs with choices directly. For instance:

parser.add_argument(
    "--list-of-xs-or-ys",
    nargs="*",
    choices=["x", "y"],
)

would allow anything like --list-of-xs-or-ys x y x y, but would complain if the user specifies anything else than x or y.


You can validate it with a custom action:

import argparse
import collections


class ValidateCredits(argparse.Action):
    def __call__(self, parser, args, values, option_string=None):
        # print '{n} {v} {o}'.format(n=args, v=values, o=option_string)
        valid_subjects = ('foo', 'bar')
        subject, credits = values
        if subject not in valid_subjects:
            raise ValueError('invalid subject {s!r}'.format(s=subject))
        credits = float(credits)
        Credits = collections.namedtuple('Credits', 'subject required')
        setattr(args, self.dest, Credits(subject, credits))

parser = argparse.ArgumentParser()
parser.add_argument('-c', '--credits', nargs=2, action=ValidateCredits,
                    help='subject followed by number of credits required',
                    metavar=('SUBJECT', 'CREDITS')
                    )
args = parser.parse_args()
print(args)
print(args.credits.subject)
print(args.credits.required)

For example,

% test.py -c foo 2
Namespace(credits=Credits(subject='foo', required=2.0))
foo
2.0
% test.py -c baz 2
ValueError: invalid subject 'baz'
% test.py -c foo bar
ValueError: could not convert string to float: bar