6.20.4.2 How callbacks are called

All callbacks are called as follows:

func(option, opt, value, parser, *args, **kwargs)

where

option
is the Option instance that's calling the callback.

opt
is the option string seen on the command-line that's triggering the callback. (If an abbreviated long option was used, opt will be the full, canonical option string--for example, if the user puts --foo on the command-line as an abbreviation for --foobar, then opt will be --foobar.)

value
is the argument to this option seen on the command-line. optparse will only expect an argument if type is set; the type of value will be the type implied by the option's type (see 6.20.3, ``Option types''). If type for this option is None (no argument expected), then value will be None. If "nargs > 1", value will be a tuple of values of the appropriate type.

parser
is the OptionParser instance driving the whole thing, mainly useful because you can access some other interesting data through it, as instance attributes:

parser.rargs
the current remaining argument list, i.e. with opt (and value, if any) removed, and only the arguments following them still there. Feel free to modify parser.rargs, e.g. by consuming more arguments.

parser.largs
the current set of leftover arguments, i.e. arguments that have been processed but have not been consumed as options (or arguments to options). Feel free to modify parser.largs e.g. by adding more arguments to it.

parser.values
the object where option values are by default stored. This is useful because it lets callbacks use the same mechanism as the rest of optparse for storing option values; you don't need to mess around with globals or closures. You can also access the value(s) of any options already encountered on the command-line.

args
is a tuple of arbitrary positional arguments supplied via the callback_args option attribute.

kwargs
is a dictionary of arbitrary keyword arguments supplied via callback_kwargs.

Since args and kwargs are optional (they are only passed if you supply callback_args and/or callback_kwargs when you define your callback option), the minimal callback function is:

def my_callback (option, opt, value, parser):
    pass

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