Search code examples
pythonargumentsargparseoptional-arguments

What's the difference between --option and nargs='?' in Python's argparse module?


Having read the documentation on argparse I am struggling to see the difference between the last two lines of code:

parser = argparse.ArgumentParser()
parser.add_argument('--option')
parser.add_argument('option', nargs='?')

Both specify optional parameters that can be passed into the parser, but why use one over the other?


Solution

  • Any argument that starts with - and -- can be used in any order (like **kwargs) whereas an argument without the dash prefix is known as a positional argument (like *args).

    Positional arguments must be provided in the order in which they are defined. A good example of using nargs='?', is to provide a method of redirecting the results of your script to a file. You specify the final argument to be an optional destination file, if the option is not provided the output is simply written to stdout.

    From a convention point of view, you can consider prefixed arguments as optional flags whereas positional arguments are required.