Python add constant values to argparse parameter
<p>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.</p>

<p>e.g.</p>

<pre><code>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']
</code></pre>

<p>Inspired by <a href="http://stackoverflow.com/questions/8526675/python-argparse-optional-append-argument-with-choices">python argparse - optional append argument with choices</a>, this may be a little overkill, but it may be useful for others that want to use sets and add constant values to options:</p>

<pre><code>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'])
</code></pre>

<p>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 <code>DEFAULT</code> in <code>add_argument</code> definition.</p>

python argparse