why parseargs stores the argument inside a list

I have an argparse that is given a string:

def f():
    return 'dummy2'

p = argparse.ArgumentParser()
p.add_argument('--a', nargs=1, type=str)
p.add_argument('--b', nargs='?', const=f(), default=f())
p.parse_args('--a dummy'.split())

The parser namespace is Namespace(a=['dummy'], b='dummy2').

How can I make the argument for a be stored as a string and not as a list of strings?

1 answer

  • answered 2019-02-10 12:23 Óscar López

    It's simple, just skip the argument for nargs. Try this:

    p = argparse.ArgumentParser()
    p.add_argument('--a', type=str)
    p.add_argument('--b', nargs='?', const=f(), default=f())
    

    I believe this is what you expected:

    p.parse_args('--a dummy'.split())
    => Namespace(a='dummy', b='dummy2')
    

    Quoting the docs:

    ArgumentParser objects usually associate a single command-line argument with a single action to be taken. The nargs keyword argument associates a different number of command-line arguments with a single action. The supported values are:

    N (an integer). N arguments from the command line will be gathered together into a list ... Note that nargs=1 produces a list of one item. This is different from the default, in which the item is produced by itself.