3

I have googled this around but can't seem to find if this question has been asked already. I want to have a value (say "blah") to be always present for a list option, plus additional arguments if they are provided.

e.g.

import argparse
args = argparse.ArgumentParser()
args.add_argument("--foo", nargs="+")

args = args.parse_args(["--foo", "bar1", "bar2", "bar3"])
args.foo.append("blah")


print args.foo
['bar1', 'bar2', 'bar3', 'blah']
Alex
  • 1,315
  • 4
  • 16
  • 29

2 Answers2

2

Inspired by python argparse - optional append argument with choices, this may be a little overkill, but it may be useful for others that want to use sets and add constant values to options:

import argparse
DEFAULT = set(['blah'])
class DefaultSet(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        default_set = DEFAULT
        if values:
            default_set.update(v)

        setattr(namespace, self.dest, default_set)

args = argparse.ArgumentParser()
args.add_argument("--foo", default=DEFAULT, action=DefaultSet,nargs="+")

args = args.parse_args(["--foo", "bar1", "bar2", "bar3"])

print args.foo
set(['bar1', 'blah', 'bar3', 'bar2'])

The only problem is that the custom action is only called when foo is specified with at least 1 argument. That is why I had to include DEFAULT in add_argument definition.

Community
  • 1
  • 1
Alex
  • 1,315
  • 4
  • 16
  • 29
0

argparse has no facility to add a fixed set of values to nargs lists.

Just do what you already do and explicitly append to the list produced.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Yeah I thought about that, but it doesn't seem elegant and pythonic. I thought of playing with ```type``` in argparse, but that looks even less so. – Alex Aug 26 '16 at 09:09
  • 2
    @Alex: I'm not sure that it is un-pythonic. You are asking way more of `argparse` than it was designed to do; if your application always needs to process a few extra names over what is specified on the command-line, then adding those to the list afterwards is *perfectly fine*. I'd say being explicit like that is actually more Pythonic. – Martijn Pieters Aug 26 '16 at 09:10