Using 'argparse.ArgumentError' in Python

Question:

I’d like to use the ArgumentError exception in the argparse module in Python, but I can’t figure out how to use it. The signature says that it should be called as ArgumentError(argument, message), but I can’t figure out what argument should be. I think it should be some part of the parser object, but I couldn’t find any documentation for it.

Asked By: asmeurer

||

Answers:

From the source documentation:

ArgumentError: The exception raised by ArgumentParser objects when there are errors with the parser’s actions. Errors raised while parsing the command-line are caught by ArgumentParser and emitted as command-line messages.

The argument parameter of the constructor is the Action object from which the exception is raised. Usually there is no need to raise it outside of an Action subclass, and when subclassing it, there is no need to raise it explicitly; you usually raise ValueError (or whatever is appropriate) instead.

Float values between 0 and 1

In regards to your comment, that you only want to accept floating point values between 0 and 1. For this you should use the ability to define custom types. You can do it for example like this:

def percentFloat (string):
    value = float(string)
    if value < 0 or value > 1:
        raise argparse.ArgumentTypeError('Value has to be between 0 and 1')
    return value

parser = argparse.ArgumentParser()
parser.add_argument('test', type=percentFloat)
parser.parse_args()

Note that this is also safe against non-floats as float(string) will raise a ValueError for non-floats which also triggers an invalid type error by the argparse module. ArgumentTypeError is just a way to specify a custom error message.

Mutually exclusive parameters

For mutually exclusive parameters, you should use argparse.add_mutually_exclusive_group.

Parameter dependency

Parameter dependency isn’t really something that should be done by the argument parser. For semantic details, you should instead simply do it yourself:

args = parser.parse_args()
if args.w and not args.p:
    parser.error('-p is required when -w is set.')

You can use ArgumentParser.error to raise custom error message which will interrupt the program and print to the console.

But of course in such a basic situation it would make a lot more sense just to implicitly guess -p if possible.

Answered By: poke

While parser.error() is what most people probably want, it is also possible to use argparse.ArgumentError() (as the question asks.) You need a reference to the argument, like the bar_arg in the example below:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--foo')
bar_arg = parser.add_argument('--bar')

args = parser.parse_args()
if args.bar == 'xyzzy':
    raise argparse.ArgumentError(bar_arg, "Can't be 'xyzzy'")

if args.foo == 'xyzzy':
    parser.error("Can't be 'xyzzy'")

This will result in output like the one below:

$ python argparse_test.py --foo xyzzy
usage: argparse_test.py [-h] [--foo FOO] [--bar BAR]
argparse_test.py: error: Can't be 'xyzzy'

$ python argparse_test.py --bar xyzzy
Traceback (most recent call last):
  File "argparse_test.py", line 10, in <module>
    raise argparse.ArgumentError(bar_arg, "Can't be 'xyzzy'")
argparse.ArgumentError: argument --bar: Can't be 'xyzzy'
Answered By: ukrutt
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.