[issue9625] argparse: Problem with defaults for variable nargs when using choices

Martin Pengelly-Phillips report at bugs.python.org
Mon Jan 23 23:23:15 CET 2012


Martin Pengelly-Phillips <dev at thesociable.net> added the comment:

The real issue is that the choices flag does not work with a default flag and * nargs.

The following works as expected:
>>> parser.add_argument('chosen', nargs='*', default=['a'])
>>> print(parser.parse_args())
Namespace(chosen=['a'])
>>> print(parser.parse_args(['a', 'b']))
Namespace(chosen=['a', 'b'])

Introducing a choices constraint breaks down when using the defaults:
>>> parser.add_argument('chosen', nargs='*', default=['a'], choices=['a', 'b'])
>>> print(parser.parse_args(['a']))
Namespace(chosen=['a'])
>>> print(parser.parse_args())
error: argument chosen: invalid choice: ['a'] (choose from 'a', 'b')

I would expect instead to have Namespace.chosen populated with the default list as before, but the choices constraint check does not validate correctly.

I think that changing the choices constraint logic to iterate over the default values if nargs results in a list would be a possible solution.

----------
title: argparse: Problem with defaults for variable nargs -> argparse: Problem with defaults for variable nargs when using choices

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue9625>
_______________________________________


More information about the Python-bugs-list mailing list