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.
I’d like to use the ArgumentError exception in the argparse module in Python, but
Share
From the source documentation:
The
argumentparameter of the constructor is theActionobject from which the exception is raised. Usually there is no need to raise it outside of anActionsubclass, and when subclassing it, there is no need to raise it explicitly; you usually raiseValueError(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:
Note that this is also safe against non-floats as
float(string)will raise aValueErrorfor non-floats which also triggers an invalid type error by theargparsemodule.ArgumentTypeErroris 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:
You can use
ArgumentParser.errorto 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
-pif possible.