Optik Reference Guide   
=====================

Creating the parser
-------------------

The first step in using Optik is to create an OptionParser instance::

  parser = OptionParser(...)

The OptionParser constructor has no required arguments, but a number of
optional keyword arguments.  You should always pass them as keyword
arguments, i.e. do not rely on the order in which the arguments are
declared.

  ``usage`` (default: ``"%prog [options]"``)
    The usage summary to print when your program is run incorrectly or
    with a help option.  When Optik prints the usage string, it expands
    ``%prog`` to ``os.path.basename(sys.argv[0])`` (or to ``prog`` if
    you passed that keyword argument).  To suppress a usage message,
    pass the special value ``optik.SUPPRESS_USAGE``.

  ``option_list`` (default: ``[]``)
    A list of Option objects to populate the parser with.  The options
    in ``option_list`` are added after any options in
    ``standard_option_list`` (a class attribute that may be set by
    OptionParser subclasses), but before any version or help options.
    Deprecated; use ``add_option()`` after creating the parser instead.

  ``option_class`` (default: optik.option.Option)
    Class to use when adding options to the parser in ``add_option()``.

  ``version`` (default: ``None``)
    A version string to print when the user supplies a version option.
    If you supply a true value for ``version``, Optik automatically adds
    a version option with the single option string ``"--version"``.  The
    substring ``"%prog"`` is expanded the same as for ``usage``.

  ``conflict_handler`` (default: ``"error"``)
    Specifies what to do when options with conflicting option strings
    are added to the parser; see `Conflicts between options`_.

  ``description`` (default: ``None``)
    A paragraph of text giving a brief overview of your program.  Optik
    reformats this paragraph to fit the current terminal width and
    prints it when the user requests help (after ``usage``, but before
    the list of options).

  ``formatter`` (default: a new IndentedHelpFormatter)
    An instance of optik.help.HelpFormatter that will be used for
    printing help text.  Optik provides two concrete classes for this
    purpose: IndentedHelpFormatter and TitledHelpFormatter.

  ``add_help_option`` (default: ``True``)
    If true, Optik will add a help option (with option strings ``"-h"``
    and ``"--help"``) to the parser.

  ``prog``
    The string to use when expanding ``"%prog"`` in ``usage`` and
    ``version`` instead of ``os.path.basename(sys.argv[0])``.


Populating the parser
---------------------

There are several ways to populate the parser with options.  The
preferred way is by using ``OptionParser.add_option()``, as shown in
`the tutorial`_.  ``add_option()`` can be called in one of two
ways:

* pass it an Option instance (as returned by ``make_option()``)
* pass it any combination of positional and keyword arguments that are
  acceptable to ``make_option()`` (i.e., to the Option constructor),
  and it will create the Option instance for you

.. _the tutorial: tutorial.html

The other alternative is to pass a list of pre-constructed Option
instances to the OptionParser constructor, as in::

  option_list = [
      make_option("-f", "--filename",
                  action="store", type="string", dest="filename"),
      make_option("-q", "--quiet",
                  action="store_false", dest="verbose"),
      ]
  parser = OptionParser(option_list=option_list)

(``make_option()`` is a factory function for creating Option instances;
currently it is an alias for the Option constructor.  A future version
of Optik may split Option into several classes, and ``make_option()``
will pick the right class to instantiate.  Do not instantiate Option
directly.)


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 with the
``add_option()`` method of ``OptionParser``::

  parser.add_option(opt_str[, ...], attr=value, ...)

To define an option with only a short option string::

  parser.add_option("-f", attr=value, ...)

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

  parser.add_option("--foo", attr=value, ...)

The keyword arguments define attributes of the new Option object.  The
most important option attribute is ``action``, and it largely determines
which other attributes are relevant or required.  If you pass irrelevant
option attributes, or fail to pass required ones, Optik raises an
OptionError exception explaining your mistake.

An options's *action* determines what Optik does when it encounters this
option on the command-line.  The standard option actions hard-coded into
Optik 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
``append_const``
    append a constant value 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.  Optik always creates a special object for this,
conventionally called ``options`` (it happens to be an instance of
``optik.Values``).  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 Optik does is create the ``options`` object::

  options = Values()

If one of the options in this parser is defined with ::

  parser.add_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 Optik, on seeing this 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.


Standard option actions
-----------------------

The various option actions all have slightly different requirements and
effects.  Most actions have several relevant option attributes which you
may specify to guide Optik's behaviour; a few have required attributes,
which you must specify for any option using that action.

* ``store`` [relevant: ``type``, ``dest``, ``nargs``, ``choices``]

  The option must be followed by an argument, which is
  converted to a value according to ``type`` and stored in
  ``dest``.  If ``nargs`` > 1, multiple arguments will be consumed
  from the command line; all will be converted according to
  ``type`` and stored to ``dest`` as a tuple.  See the "Option
  types" section below.

  If ``choices`` is supplied (a list or tuple of strings), the type
  defaults to ``choice``.

  If ``type`` is not supplied, it defaults to ``string``.

  If ``dest`` is not supplied, Optik derives a destination from the
  first long option string (e.g., ``"--foo-bar"`` implies ``foo_bar``).
  If there are no long option strings, Optik derives a destination from
  the first short option string (e.g., ``"-f"`` implies ``f``).

  Example::

    parser.add_option("-f")
    parser.add_option("-p", type="float", nargs=3, dest="point")

  As it parses the command line ::

    -f foo.txt -p 1 -3.5 4 -fbar.txt

  Optik will set ::

    options.f = "foo.txt"
    options.point = (1.0, -3.5, 4.0)
    options.f = "bar.txt"

* ``store_const`` [required: ``const``; relevant: ``dest``]

  The value ``const`` is stored in ``dest``.

  Example::

    parser.add_option("-q", "--quiet",
                      action="store_const", const=0, dest="verbose")
    parser.add_option("-v", "--verbose",
                      action="store_const", const=1, dest="verbose")
    parser.add_option("--noisy",
                      action="store_const", const=2, dest="verbose")

  If ``"--noisy"`` is seen, Optik will set ::

    options.verbose = 2

* ``store_true`` [relevant: ``dest``]

  A special case of ``store_const`` that stores a true value
  to ``dest``.

* ``store_false`` [relevant: ``dest``]

  Like ``store_true``, but stores a false value.

  Example::

    parser.add_option("--clobber", action="store_true", dest="clobber")
    parser.add_option("--no-clobber", action="store_false", dest="clobber")

* ``append`` [relevant: ``type``, ``dest``, ``nargs``, ``choices``]

  The option must be followed by an argument, which is appended to the
  list in ``dest``.  If no default value for ``dest`` is supplied, an
  empty list is automatically created when Optik first encounters this
  option on the command-line.  If ``nargs`` > 1, multiple arguments are
  consumed, and a tuple of length ``nargs`` is appended to ``dest``.

  The defaults for ``type`` and ``dest`` are the same as for the
  ``store`` action.

  Example::

    parser.add_option("-t", "--tracks", action="append", type="int")

  If ``"-t3"`` is seen on the command-line, Optik does the equivalent of::

    options.tracks = []
    options.tracks.append(int("3"))

  If, a little later on, ``"--tracks=4"`` is seen, it does::

    options.tracks.append(int("4"))

* ``append_const`` [required: ``const``; relevant: ``dest``]

  Like ``store_const``, but the value ``const`` is appended to ``dest``;
  as with ``append``, ``dest`` defaults to ``None``, and an an empty list is
  automatically created the first time the option is encountered.

* ``count`` [relevant: ``dest``]

  Increment the integer stored at ``dest``.  If no default value is
  supplied, ``dest`` is set to zero before being incremented the first
  time.

  Example::

    parser.add_option("-v", action="count", dest="verbosity")

  The first time ``"-v"`` is seen on the command line, Optik does the
  equivalent of::

    options.verbosity = 0
    options.verbosity += 1

  Every subsequent occurrence of ``"-v"`` results in ::

    options.verbosity += 1

* ``callback`` [required: ``callback``;
  relevant: ``type``, ``nargs``, ``callback_args``, ``callback_kwargs``]

  Call the function specified by ``callback``, which is called as ::

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

  See `Option Callbacks`_ for more detail.

  .. _Option Callbacks: callbacks.html

* ``help``

  Prints a complete help message for all the options in the
  current option parser.  The help message is constructed from
  the ``usage`` string passed to OptionParser's constructor and
  the ``help`` string passed to every option.

  If no ``help`` string is supplied for an option, it will still be
  listed in the help message.  To omit an option entirely, use
  the special value ``optik.SUPPRESS_HELP``.

  Optik automatically adds a ``help`` option to all OptionParsers, so
  you do not normally need to create one.

  Example::

    from optik import OptionParser, SUPPRESS_HELP

    parser = OptionParser()
    parser.add_option("-h", "--help", action="help"),
    parser.add_option("-v", action="store_true", dest="verbose",
                      help="Be moderately verbose")
    parser.add_option("--file", dest="filename",
                      help="Input file to read data from"),
    parser.add_option("--secret", help=SUPPRESS_HELP)

  If Optik sees either ``"-h"`` or ``"--help"`` on the command line, it
  will print something like the following help message to stdout
  (assuming ``sys.argv[0]`` is ``"foo.py"``)::

    usage: foo.py [options]

    options:
      -h, --help        Show this help message and exit
      -v                Be moderately verbose
      --file=FILENAME   Input file to read data from

  After printing the help message, Optik terminates your process
  with ``sys.exit(0)``.

* ``version``

  Prints the version number supplied to the OptionParser to stdout and
  exits.  The version number is actually formatted and printed by the
  ``print_version()`` method of OptionParser.  Generally only relevant
  if the ``version`` argument is supplied to the OptionParser
  constructor.  As with ``help`` options, you will rarely create
  ``version`` options, since Optik automatically adds them when needed.


Option attributes
-----------------

The following option attributes may be passed as keyword arguments
to ``parser.add_option()``.  If you pass an option attribute
that is not relevant to a particular option, or fail to pass a required
option attribute, Optik raises OptionError.

* ``action`` (default: ``"store"``)

  Determines Optik's behaviour when this option is seen on the command
  line; the available options are documented above.  

* ``type`` (default: ``"string"``)

  The argument type expected by this option (e.g., ``"string"`` or
  ``"int"``); the available option types are documented below.


* ``dest`` (default: derived from option strings)

  If the option's action implies writing or modifying a value somewhere,
  this tells Optik where to write it: ``dest`` names an attribute of the
  ``options`` object that Optik builds as it parses the command line.

* ``default`` (deprecated)

  The value to use for this option's destination if the option is not
  seen on the command line.  Deprecated; use ``parser.set_defaults()``
  instead.

* ``nargs`` (default: 1)

  How many arguments of type ``type`` should be consumed when this
  option is seen.  If > 1, Optik will store a tuple of values to
  ``dest``.

* ``const``

  For actions that store a constant value, the constant value to store.

* ``choices``

  For options of type ``"choice"``, the list of strings the user
  may choose from.

* ``callback``

  For options with action ``"callback"``, the callable to call when this
  option is seen.  See `Option Callbacks`_ for detail on the arguments
  passed to ``callable``.

* ``callback_args``, ``callback_kwargs``

  Additional positional and keyword arguments to pass to ``callback``
  after the four standard callback arguments.

* ``help``

  Help text to print for this option when listing all available options
  after the user supplies a ``help`` option (such as ``"--help"``).
  If no help text is supplied, the option will be listed without help
  text.  To hide this option, use the special value ``SUPPRESS_HELP``.

* ``metavar`` (default: derived from option strings)

  Stand-in for the option argument(s) to use when printing help text.
  See `the tutorial`_ for an example.


Standard option types
---------------------

Optik has six built-in option types: ``string``, ``int``, ``long``,
``choice``, ``float`` and ``complex``.  If you need to add new option
types, see `Extending Optik`_.

.. _Extending Optik: extending.html

Arguments to string options are not checked or converted in any way: the
text on the command line is stored in the destination (or passed to the
callback) as-is.

Integer arguments (type ``int`` or ``long``) are parsed as follows:

  * if the number starts with ``0x``, it is parsed as a hexadecimal number
  * if the number starts with ``0``, it is parsed as an octal number
  * if the number starts with ``0b``, is is parsed as a binary number
  * otherwise, the number is parsed as a decimal number

The conversion is done by calling either ``int()`` or ``long()`` with
the appropriate base (2, 8, 10, or 16).  If this fails, so will Optik,
although with a more useful error message.

``float`` and ``complex`` option arguments are converted directly with
``float()`` and ``complex()``, with similar error-handling.

``choice`` options are a subtype of ``string`` options.  The ``choices``
option attribute (a sequence of strings) defines the set of allowed
option arguments.  ``optik.option.check_choice()`` compares
user-supplied option arguments against this master list and raises
OptionValueError if an invalid string is given.


Parsing arguments
-----------------

The whole point of creating and populating an OptionParser is to call
its ``parse_args()`` method::

  (options, args) = parser.parse_args(args=None, options=None)

where the input parameters are

``args``
  the list of arguments to process (default: ``sys.argv[1:]``)
``options``
  object to store option arguments in (default: a new instance of
  optik.Values)

and the return values are

``options``
  the same object that was passed in as ``options``, or the
  optik.Values instance created by Optik
``args``
  the leftover positional arguments after all options have been
  processed

The most common usage is to supply neither keyword argument.  If you
supply ``options``, it will be modified with repeated ``setattr()``
calls (roughly one for every option argument stored to an option
destination) and returned by ``parse_args()``.

If ``parse_args()`` encounters any errors in the argument list, it calls
the OptionParser's ``error()`` method with an appropriate end-user error
message.  This ultimately terminates your process with an exit status of
2 (the traditional UNIX exit status for command-line errors).


Querying and manipulating your option parser
--------------------------------------------

Sometimes, it's useful to poke around your option parser and see what's
there.  OptionParser provides a couple of methods to help you out:

``has_option(opt_str)``
    Return true if the OptionParser has an option with 
    option string ``opt_str`` (e.g., ``"-q"`` or ``"--verbose"``).

``get_option(opt_str)``
    Returns the Option instance with the option string ``opt_str``, or
    ``None`` if no options have that option string.

``remove_option(opt_str)``
    If the OptionParser has an option corresponding to ``opt_str``,
    that option is removed.  If that option provided any other
    option strings, all of those option strings become invalid.
    If ``opt_str`` does not occur in any option belonging to this
    OptionParser, raises ValueError.


.. _Conflicts between options:

Conflicts between options
-------------------------

If you're not careful, it's easy to define options with conflicting
option strings::

  parser.add_option("-n", "--dry-run", ...)
  [...]
  parser.add_option("-n", "--noisy", ...)

(This is particularly true if you've defined your own OptionParser
subclass with some standard options.)

Every time you add an option, Optik checks for conflicts with existing
options.  If it finds any, it invokes the current conflict-handling
mechanism.  You can set the conflict-handling mechanism either in the
constructor::

  parser = OptionParser(..., conflict_handler=handler)

or with a separate call::

  parser.set_conflict_handler(handler)

The available conflict handlers are:

  ``error`` (default)
    assume option conflicts are a programming error and raise 
    OptionConflictError
  ``resolve``
    resolve option conflicts intelligently (see below)

As an example, let's define an OptionParser that resolves conflicts
intelligently and add conflicting options to it::

  parser = OptionParser(conflict_handler="resolve")
  parser.add_option("-n", "--dry-run", ..., help="do no harm")
  parser.add_option("-n", "--noisy", ..., help="be noisy")

At this point, Optik detects that a previously-added option is already
using the ``"-n"`` option string.  Since ``conflict_handler`` is
``"resolve"``, it resolves the situation by removing ``"-n"`` from the
earlier option's list of option strings.  Now ``"--dry-run"`` is the
only way for the user to activate that option.  If the user asks for
help, the help message will reflect that::

  options:
    --dry-run     do no harm
    [...]
    -n, --noisy   be noisy

It's possible to whittle away the option strings for a previously-added
option until there are none left, and the user has no way of invoking
that option from the command-line.  In that case, Optik removes that
option completely, so it doesn't show up in help text or anywhere else.
Carrying on with our existing OptionParser::

  parser.add_option("--dry-run", ..., help="new dry-run option")

At this point, the original ``-n/--dry-run`` option is no longer
accessible, so Optik removes it, leaving this help text::

  options:
    [...]
    -n, --noisy   be noisy
    --dry-run     new dry-run option


Cleanup
-------

OptionParser instances have several cyclic references.  This should not
be a problem for Python's garbage collector, but you may wish to break
the cyclic references explicitly by calling ``destroy()`` on your
OptionParser once you are done with it.  This is particularly useful in
long-running applications where large object graphs are reachable from
your OptionParser.


Other methods
-------------

OptionParser supports several other public methods:

* ``set_usage(usage)``

  Set the usage string according to the rules described above for the
  ``usage`` constructor keyword argument.  Passing ``None`` sets the
  default usage string; use ``SUPPRESS_USAGE`` to suppress a usage
  message.

* ``enable_interspersed_args()``, ``disable_interspersed_args()``

  Enable/disable positional arguments interspersed with options, similar
  to GNU getopt (enabled by default).  For example, if ``"-a"`` and
  ``"-b"`` are both simple options that take no arguments, Optik
  normally accepts this syntax::

    prog -a arg1 -b arg2

  and treats it as equivalent to ::

    prog -a -b arg1 arg2

  To disable this feature, call ``disable_interspersed_args()``.  This
  restores traditional UNIX syntax, where option parsing stops with the
  first non-option argument.

* ``set_defaults(dest=value, ...)``

  Set default values for several option destinations at once.  Using
  ``set_defaults()`` is the preferred way to set default values for
  options, since multiple options can share the same destination.  For
  example, if several "mode" options all set the same destination, any
  one of them can set the default, and the last one wins::

    parser.add_option("--advanced", action="store_const",
                      dest="mode", const="advanced",
                      default="novice")    # overridden below
    parser.add_option("--novice", action="store_const",
                      dest="mode", const="novice",
                      default="advanced")  # overrides above setting

  To avoid this confusion, use ``set_defaults()``::

    parser.set_defaults(mode="advanced")
    parser.add_option("--advanced", action="store_const",
                      dest="mode", const="advanced")
    parser.add_option("--novice", action="store_const",
                      dest="mode", const="novice")


.. $Id: reference.txt 519 2006-06-11 14:39:11Z gward $
