Problem with defaults for variable nargs

9 views
Skip to first unread message

Martin

unread,
Aug 16, 2010, 10:42:16 AM8/16/10
to argparse-users
Hi there,

Been using argparse a while and this little niggle comes up every once
in a while:

---
parser = argparse.ArgumentParser()
parser.add_argument('choices', nargs='*', default='a', choices=['a',
'b', 'c'])

args = parser.parse_args()
print type(args.choices)
# str

args = parser.parse_args(['a'])
print type(args.choices)
# list
---

If the user specifies the value then a list is used otherwise a string
is used.
Tried changing default to a list value, but then get :
error: argument choices: invalid choice: ['a'] (choose from 'a', 'b',
'c')

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

I'll try to take a look at the source sometime to see if I can work
out a patch to fix this behaviour.
In the meantime if it is a quick fix on your end it would be much
appreciated.

ta,


Martin


Steven Bethard

unread,
Aug 16, 2010, 12:58:25 PM8/16/10
to argpars...@googlegroups.com
On Mon, Aug 16, 2010 at 4:42 PM, Martin <d...@thesociable.net> wrote:
> Been using argparse a while and this little niggle comes up every once
> in a while:

>>> parser = argparse.ArgumentParser()


>>> parser.add_argument('choices', nargs='*', default=['a'], choices=['a', 'b', 'c'])

>>> parser.parse_args()
usage: [-h] [{a,b,c} [{a,b,c} ...]]


: error: argument choices: invalid choice: ['a'] (choose from 'a', 'b', 'c')

Yeah, this is a bad interaction between choices and nargs='*'. When
you have a chance, please file a bug report at bugs.python.org, so
this doesn't get lost. In the meantime, a workaround is to pass a
type= argument instead with something like:

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

Steve
--
Where did you get that preposterous hypothesis?
Did Steve tell you that?
        --- The Hiphopopotamus

Martin

unread,
Aug 17, 2010, 5:20:51 AM8/17/10
to argparse-users
Hi Steve,

Thanks for the quick response and workaround.
Bug filed here: http://bugs.python.org/issue9625

ta,

Martin
Reply all
Reply to author
Forward
0 new messages