29

I just noticed a behavior in argparse that puzzled me (guess I'd never used it for a dumb list of files before):

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('multi', action='append', nargs='+')
print(parser.parse_args())

This gives me the output:

~$ ./testargs.py foo bar baz
Namespace(multi=[['foo', 'bar', 'baz']])
~$ 

I expected multi to be ['foo', 'bar', 'baz'], not a list within a list. As-is, I'll have to grab args.multi[0] before processing, which isn't a big deal, but feels like an ugly wart, and I'd like to understand why it's there.

Am I doing something silly in add_argument, or is this just an unavoidable quirk?

Nicholas Knight
  • 15,774
  • 5
  • 45
  • 57

1 Answers1

37

You are calling

parser.add_argument('multi', action='append', nargs='+')

And it is taking all the arguments and appending as a single item in the multi list.

If you want it as individual items, just don't use append

parser.add_argument('multi', nargs='+')

From the docs

'append' - This stores a list, and appends each argument value to the list. This is useful to allow an option to be specified multiple times. Example usage:

>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='append')
>>> parser.parse_args('--foo 1 --foo 2'.split())
Namespace(foo=['1', '2'])
stephenmm
  • 2,640
  • 3
  • 30
  • 48
Senthil Kumaran
  • 54,681
  • 14
  • 94
  • 131
  • 2
    Huh, you're right. I got the wrong impression from the docs. Maybe I should see if I can send a patch with better wording on a few things. :) Thanks! – Nicholas Knight Mar 03 '11 at 05:18
  • 4
    However, note that without `action='append'`, previous values will be discarded if the option is specified multiple times. e.g. `argv=['--foo', 'a', 'b', '--foo', 'c']` will give `Namespace(foo=['c'])` for `add_argument('--foo', nargs='+')`. – mic_e May 19 '16 at 11:21
  • Is there a way to have both options? Multiple --foo or single --foo argument resulting in a single list of strings? – daniels_pa May 10 '22 at 05:42