6.20.3.2 Defining options

Each Option instance represents a set of synonymous command-line option strings, e.g. -f and --file. You can specify any number of short or long option strings, but you must specify at least one overall option string.

The canonical way to create an Option instance is by calling make_option(), so that is what will be shown here. However, the most common and convenient way is to use parser.add_option(). Note that make_option() and parser.add_option() have identical call signatures:

make_option(opt_str, ..., attr=value, ...)
parser.add_option(opt_str, ..., attr=value, ...)

To define an option with only a short option string:

make_option("-f", attr=value, ...)

And to define an option with only a long option string:

make_option("--foo", attr=value, ...)

The attr=value keyword arguments define option attributes, i.e. attributes of the Option object. The most important option attribute is action, and it largely determines what other attributes are relevant or required. If you pass irrelevant option attributes, or fail to pass required ones, optparse raises an OptionError exception explaining your mistake.

An options's action determines what optparse does when it encounters this option on the command-line. The actions hard-coded into optparse are:

store
store this option's argument [default]
store_const
store a constant value
store_true
store a true value
store_false
store a false value
append
append this option's argument to a list
count
increment a counter by one
callback
call a specified function
help
print a usage message including all options and the documentation for them

(If you don't supply an action, the default is store. For this action, you may also supply type and dest option attributes; see below.)

As you can see, most actions involve storing or updating a value somewhere. optparse always creates an instance of optparse.Values specifically for this purpose; we refer to this instance as options. Option arguments (and various other values) are stored as attributes of this object, according to the dest (destination) option attribute.

For example, when you call

parser.parse_args()

one of the first things optparse does is create the options object:

options = Values()

If one of the options in this parser is defined with

make_option("-f", "--file", action="store", type="string", dest="filename")

and the command-line being parsed includes any of the following:

-ffoo
-f foo
--file=foo
--file foo

then optparse, on seeing the -f or --file option, will do the equivalent of

options.filename = "foo"

The type and dest option attributes are almost as important as action, but action is the only one that makes sense for all options.

See About this document... for information on suggesting changes.