[New-bugs-announce] [issue41047] argparse: misbehavior when combining positionals and choices

James Corbett report at bugs.python.org
Fri Jun 19 22:15:23 EDT 2020


New submission from James Corbett <james.h.corbett at gmail.com>:

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.

----------
components: Library (Lib)
messages: 371915
nosy: jameshcorbett
priority: normal
severity: normal
status: open
title: argparse: misbehavior when combining positionals and choices
type: behavior
versions: Python 3.9

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue41047>
_______________________________________


More information about the New-bugs-announce mailing list