ArgParse.jl
ArgParse.jl copied to clipboard
equivalent of python argparse choices?
Is there an equivalent to python argparse choice, e.g.:
parser.add_argument ('--rate', choices=('1/3', '1/2', '2/3', '3/4', '3/5', '4/5', '5/6', '7/9', '8/9', '9/10', '25/36', '26/45'), default='2/3')
No, but it's rather easy to implement it without much extra typing compared to a built-in version:
using ArgParse
function main(args)
s = ArgParseSettings("Example of choice")
choices = ["1/3", "1/2", "2/3", "3/4", "3/5", "4/5", "5/6",
"7/9", "8/9", "9/10", "25/36", "26/45"]
@add_arg_table s begin
"--rate"
default = "2/3"
range_tester = (x->x ∈ choices)
help = "rate; must be one of " * join(choices, ", ", " or ")
end
parsed_args = parse_args(args, s)
@show parsed_args["rate"]
end
main(ARGS)
$ julia choices.jl --help
usage: choices.jl [--rate RATE] [-h]
Example of choice
optional arguments:
--rate RATE rate; must be one of 1/3, 1/2, 2/3, 3/4, 3/5, 4/5, 5/6,
7/9, 8/9, 9/10, 25/36 or 26/45 (default: "2/3")
-h, --help show this help message and exit
Thanks for the example @carlobaldassi. Still, it would be convenient to have choices
built-in like in Python, because it's just such a common pattern.
+1 for this feature.
I would also like to see choices
built-in. Especially as the error message is otherwise misleading.
I would also like to see
choices
built-in. Especially as the error message is otherwise misleading.
I think this is the biggest reason to have this feature built-in, so that the error can be automatically generated without the programmer's intervention.