Python argparse: Is there a way to specify a range in nargs?

Each Answer to this Q is separated by one/two green lines.

I have an optional argument that supports a list of arguments itself.

I mean, it should support:

  • -f 1 2
  • -f 1 2 3

but not:

  • -f 1
  • -f 1 2 3 4

Is there a way to force this within argparse ? Now I’m using nargs=”*”, and then checking the list length.

Edit: As requested, what I needed is being able to define a range of acceptable number of arguments. I mean, saying (in the example) 2 or 3 args is right, but not 1 or 4 or anything that’s not inside the range 2..3

You could do this with a custom action:

import argparse

def required_length(nmin,nmax):
    class RequiredLength(argparse.Action):
        def __call__(self, parser, args, values, option_string=None):
            if not nmin<=len(values)<=nmax:
                msg='argument "{f}" requires between {nmin} and {nmax} arguments'.format(
                raise argparse.ArgumentTypeError(msg)
            setattr(args, self.dest, values)
    return RequiredLength

parser.add_argument('-f', nargs="+", action=required_length(2,3))

args=parser.parse_args('-f 1 2 3'.split())
# ['1', '2', '3']

    args=parser.parse_args('-f 1 2 3 4'.split())
except argparse.ArgumentTypeError as err:
# argument "f" requires between 2 and 3 arguments

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .