ArgParse.jl icon indicating copy to clipboard operation
ArgParse.jl copied to clipboard

equivalent of python argparse choices?

Open nbecker opened this issue 8 years ago • 5 comments

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')

nbecker avatar Feb 02 '17 19:02 nbecker

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

carlobaldassi avatar Feb 03 '17 11:02 carlobaldassi

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.

epatters avatar Jan 19 '19 21:01 epatters

+1 for this feature.

petershintech avatar Aug 30 '21 02:08 petershintech

I would also like to see choices built-in. Especially as the error message is otherwise misleading.

edwinlock avatar Jul 03 '23 17:07 edwinlock

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.

jpmvferreira avatar Oct 18 '23 13:10 jpmvferreira