How to make an optional value for argument using argparse?

totokaka picture totokaka · Feb 24, 2014 · Viewed 15.1k times · Source

I am creating a python script where I want to have an argument that manipulates how many search results you get as output. I've currently named the argument --head. This is the functionality I'd like it to have:

  1. When --head is not passed at the command line I'd like it to default to one value. In this case, a rather big one, like 80

  2. When --head is passed without any value, I'd like it to default to another value. In this case, something limited, like 10

  3. When --head is passed with a value, I'd like it to store the value it was passed.

Here is some code describing the problem:

>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('-h',
                        '--head',
                        dest='size',
                        const=80,
                        default=10,
                        action="I don't know",
                        help='Only print the head of the output')
>>> # OFC, that last line will fail because the action is uknown,
... # but here is how I'd like it to work
... parser.parse_args(''.split())
Namespace(size=80)
>>> parser.parse_args('--head'.split())
Namespace(size=10)
>>> parser.parse_args('--head 15'.split())
Namespace(size=15)

I know I probably can write a custom action for this, but I first want to see if there is any default behaviour that does this.

Answer

totokaka picture totokaka · Feb 24, 2014

After a little more reading in the documentation I found what I needed: nargs='?'. This is used with the store action, and does exactly what I want.

Here is an example:

>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--head',
                        dest='size',
                        const=10,
                        default=80,
                        action='store',
                        nargs='?',
                        type=int,
                        help='Only print the head of the output')
>>> parser.parse_args(''.split())
... Namespace(size=80)
>>> parser.parse_args('--head'.split())
... Namespace(size=10)
>>> parser.parse_args('--head 15'.split())
... Namespace(size=15)

Source: http://docs.python.org/3/library/argparse.html#nargs