Author thesociable
Recipients thesociable
Date 2010-08-17.09:19:02
SpamBayes Score 1.56071e-11
Marked as misclassified No
Message-id <>
Variable argument count plays badly with choices.

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

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
Date User Action Args
2010-08-17 09:19:04thesociablesetrecipients: + thesociable
2010-08-17 09:19:04thesociablesetmessageid: <>
2010-08-17 09:19:03thesociablelinkissue9625 messages
2010-08-17 09:19:02thesociablecreate