Message371915
The `argparse.ArgumentParser` sometimes rejects positional arguments with no arguments when `choices` is set and `nargs="*"`.
When there are no arguments and `nargs` is `"*"`, the default value is chosen, or `[]` if there is no default value. This value is then checked against `choices` and an error message is printed if the value is not in `choices`. However, sometimes the value is intentionally not in `choices`, and this leads to problems. An example will explain this much better, and show that the issue only occurs with the particular combination of positionals, `nargs="*"`, and `choices`:
```
>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument("foo", choices=["a", "b", "c"], nargs="*")
>>> parser.add_argument("--bar", choices=["d", "e", "f"], nargs="*")
>>> parser.add_argument('--baz', type=int, choices=range(5, 10), default="20")
>>> parser.parse_args("a --bar".split())
Namespace(foo=['a'], bar=[], baz=20)
>>> parser.parse_args(["a"])
Namespace(foo=['a'], bar=None, baz=20)
>>> parser.parse_args([])
usage: [-h] [--bar [{d,e,f} ...]] [--baz {5,6,7,8,9}] [{a,b,c} ...]
: error: argument foo: invalid choice: [] (choose from 'a', 'b', 'c')
```
In this case I could have got around the last error by adding `[]` to choices, but that pollutes the help and usage messages. |
|
| Date |
User |
Action |
Args |
| 2020-06-20 02:15:23 | jameshcorbett | set | recipients:
+ jameshcorbett |
| 2020-06-20 02:15:23 | jameshcorbett | set | messageid: <1592619323.37.0.243911882097.issue41047@roundup.psfhosted.org> |
| 2020-06-20 02:15:23 | jameshcorbett | link | issue41047 messages |
| 2020-06-20 02:15:22 | jameshcorbett | create | |
|