Skip to content Skip to sidebar Skip to footer

Python Argparse With Nargs Behaviour Incorrect

Here is my argparse sample say sample.py import argparse parser = argparse.ArgumentParser() parser.add_argument('-p', nargs='+', help='Stuff') args = parser.parse_args() print args

Solution 1:

Note: python 3.8 adds an action="extend" which will create the desired list of ['x','y']

To produce a list of ['x','y'] use action='append'. Actually it gives

Namespace(p=[['x'], ['y']])

For each -p it gives a list ['x'] as dictated by nargs='+', but append means, add that value to what the Namespace already has. The default action just sets the value, e.g. NS['p']=['x']. I'd suggest reviewing the action paragraph in the docs.

optionals allow repeated use by design. It enables actions like append and count. Usually users don't expect to use them repeatedly, or are happy with the last value. positionals (without the -flag) cannot be repeated (except as allowed by nargs).

How to add optional or once arguments? has some suggestions on how to create a 'no repeats' argument. One is to create a custom action class.

Solution 2:

I ran into the same issue. I decided to go with the custom action route as suggested by mgilson.

import argparse
classExtendAction(argparse.Action):
  def__call__(self, parser, namespace, values, option_string=None):
    ifgetattr(namespace, self.dest, None) isNone:
      setattr(namespace, self.dest, [])
    getattr(namespace, self.dest).extend(values)
parser = argparse.ArgumentParser()
parser.add_argument("-p", nargs="+", help="Stuff", action=ExtendAction)
args = parser.parse_args()
print args

This results in

$ ./sample.py -p x -p y -p z w
Namespace(p=['x', 'y', 'z', 'w'])

Still, it would have been much neater if there was an action='extend' option in the library by default.

Post a Comment for "Python Argparse With Nargs Behaviour Incorrect"