0

I'm using some of the code from this answer, particularly the part which raises an argparse.ArgumentTypeError:

raise argparse.ArgumentTypeError(
                "argument '{f}' requires between {nmin} and {nmax} "
                "arguments".format(f=self.dest, nmin=nmin, nmax=nmax))

However, I've also tacked on the append action behavior into my subclass' __call__(), which means that one or more of these repeated arguments may be formatted incorrectly and could raise that ArgumentTypeError.

So when I use this for such an argument in a parser:

parse = argparse.ArgumentParser()
parser.add_argument("-a", "--append-arg", action=append_range(2,3), default=[])

And I get an error from typing the wrong number of arguments, I get something like this:

argparse.ArgumentTypeError: argument 'append_arg' requires between 2 and 3 arguments

Great, that's how I'd like it to be used. But now the list of arguments is named append_arg in the namespace. I'd like it to be named list_of_repeated_args or whatever. So if I do:

parser.add_argument("-a", "--append-arg", action=append_range(2,3), default=[], dest="list_of_repeated_args")

Then I get this for the error instead:

argparse.ArgumentTypeError: argument 'list_of_repeated_args' requires between 2 and 3 arguments

That's not what I wanted. Sure, I could change the function to take the name I want as an argument, but I'd like to just use the name automatically. Is there a way to do this? (i.e., what should I place instead of f=self.dest?)

Community
  • 1
  • 1
2rs2ts
  • 10,662
  • 10
  • 51
  • 95

1 Answers1

1

Figured out the solution. The __call__() method of the custom argparse.Action has the option_string argument which, according to the docs, is:

The option string that was used to invoke this action. The option_string argument is optional, and will be absent if the action is associated with a positional argument.

Sure enough, if I change the following code to use option_string instead:

raise argparse.ArgumentTypeError(
                "argument '{f}' requires between {nmin} and {nmax} "
                "arguments".format(f=option_string, nmin=nmin, nmax=nmax))

I get (assuming I'm using the abbreviated form) the desired effect:

argparse.ArgumentTypeError: argument '-a' requires between 2 and 3 arguments
2rs2ts
  • 10,662
  • 10
  • 51
  • 95