6.20.4.1 Defining a callback option

As always, you can define a callback option either by directly instantiating the Option class, or by using the add_option() method of your OptionParser object. The only option attribute you must specify is callback, the function to call:

parser.add_option("-c", callback=my_callback)

Note that you supply a function object here--so you must have already defined a function my_callback() when you define the callback option. In this simple case, optparse knows nothing about the arguments the -c option expects to take. Usually, this means that the option doesn't take any arguments - the mere presence of -c on the command-line is all it needs to know. In some circumstances, though, you might want your callback to consume an arbitrary number of command-line arguments. This is where writing callbacks gets tricky; it's covered later in this document.

There are several other option attributes that you can supply when you define an option attribute:

type
has its usual meaning: as with the ``store'' or ``append'' actions, it instructs optparse to consume one argument that must be convertible to type. Rather than storing the value(s) anywhere, though, optparse converts it to type and passes it to your callback function.

nargs
also has its usual meaning: if it is supplied and "nargs > 1", optparse will consume nargs arguments, each of which must be convertible to type. It then passes a tuple of converted values to your callback.

callback_args
a tuple of extra positional arguments to pass to the callback.

callback_kwargs
a dictionary of extra keyword arguments to pass to the callback.

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