[New-bugs-announce] [issue9625] argparse: Problem with defaults for variable nargs

Martin Pengelly-Phillips report at bugs.python.org
Tue Aug 17 11:19:04 CEST 2010


New submission from Martin Pengelly-Phillips <dev at thesociable.net>:

Variable argument count plays badly with choices.

Example:
========
>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('choices', nargs='*', default='a', choices=['a',
'b', 'c'])
>>> args = parser.parse_args()
>>> print type(args.choices)
<type 'str'>
>>> args = parser.parse_args(['a'])
>>> print type(args.choices)
<type 'list'>


If the user specifies the value on the command line then a list is used, but if the value comes from the default a string is used.
Unfortunately, changing default to a list value gives an error:
error: argument choices: invalid choice: ['a'] (choose from 'a', 'b',
'c')

Additionally, this means it is also not possible to use default=['a', 'c']. 

The current workaround is to create a custom type:

def my_type(string):
    if string not in ['a', 'b', 'c']:
        raise TypeError
    return string

----------
components: Library (Lib)
messages: 114108
nosy: thesociable
priority: normal
severity: normal
status: open
title: argparse: Problem with defaults for variable nargs
type: behavior
versions: Python 2.6

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


More information about the New-bugs-announce mailing list