• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1.. currentmodule:: argparse
2
3.. _upgrading-optparse-code:
4
5==========================
6Upgrading optparse code
7==========================
8
9Originally, the :mod:`argparse` module had attempted to maintain compatibility
10with :mod:`optparse`.  However, :mod:`optparse` was difficult to extend
11transparently, particularly with the changes required to support
12``nargs=`` specifiers and better usage messages.  When most everything in
13:mod:`optparse` had either been copy-pasted over or monkey-patched, it no
14longer seemed practical to try to maintain the backwards compatibility.
15
16The :mod:`argparse` module improves on the :mod:`optparse`
17module in a number of ways including:
18
19* Handling positional arguments.
20* Supporting subcommands.
21* Allowing alternative option prefixes like ``+`` and ``/``.
22* Handling zero-or-more and one-or-more style arguments.
23* Producing more informative usage messages.
24* Providing a much simpler interface for custom ``type`` and ``action``.
25
26A partial upgrade path from :mod:`optparse` to :mod:`argparse`:
27
28* Replace all :meth:`optparse.OptionParser.add_option` calls with
29  :meth:`ArgumentParser.add_argument` calls.
30
31* Replace ``(options, args) = parser.parse_args()`` with ``args =
32  parser.parse_args()`` and add additional :meth:`ArgumentParser.add_argument`
33  calls for the positional arguments. Keep in mind that what was previously
34  called ``options``, now in the :mod:`argparse` context is called ``args``.
35
36* Replace :meth:`optparse.OptionParser.disable_interspersed_args`
37  by using :meth:`~ArgumentParser.parse_intermixed_args` instead of
38  :meth:`~ArgumentParser.parse_args`.
39
40* Replace callback actions and the ``callback_*`` keyword arguments with
41  ``type`` or ``action`` arguments.
42
43* Replace string names for ``type`` keyword arguments with the corresponding
44  type objects (e.g. int, float, complex, etc).
45
46* Replace :class:`optparse.Values` with :class:`Namespace` and
47  :exc:`optparse.OptionError` and :exc:`optparse.OptionValueError` with
48  :exc:`ArgumentError`.
49
50* Replace strings with implicit arguments such as ``%default`` or ``%prog`` with
51  the standard Python syntax to use dictionaries to format strings, that is,
52  ``%(default)s`` and ``%(prog)s``.
53
54* Replace the OptionParser constructor ``version`` argument with a call to
55  ``parser.add_argument('--version', action='version', version='<the version>')``.
56