argparse: combine current option value with positional argument

Peter Otten __peter__ at
Tue Feb 1 13:59:07 CET 2011

I'd like to capture the current value of an option --prefix=<whatever> along 
with a positional value as it is seen by argparse.

python -p1 alpha beta -p2 gamma -p3

should result in a list

[(1, "alpha"), (1, "beta"), (2, "gamma")]

Here's a working script that uses --name=<some-value> instead of of just 

$ cat
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-p", "--prefix")
parser.add_argument("-n", "--name")

class Namespace(object):
    def __init__(self):
        self.pairs = []
        self.prefix = None
    def set_name(self, value):
        if value is not None:
            self.pairs.append((self.prefix, value))
    name = property(None, set_name)

ns = Namespace()
print ns.pairs
$ python -p1 -nalpha -nbeta -p2 -ngamma
[('1', 'alpha'), ('1', 'beta'), ('2', 'gamma')]

However, modifying the --name option to a positional with

parser.add_argument("name", nargs="*")

results in an error:

$ python -p1 alpha beta -p2 gamma
usage: [-h] [-p PREFIX] [name [name ...]] error: unrecognized arguments: gamma

Am I missing a simple way to avoid that?


PS: I've not yet "used the source" ;)

More information about the Python-list mailing list