Is there a way to make Python’s optparse print the default value of an option or flag when showing the help with –help?

Try using the %default string placeholder:

# This example taken from
parser.add_option("-m", "--mode",
                  help="interaction mode: novice, intermediate, "
                       "or expert [default: %default]")

And if you want to add default values automatically to all options that you have specified, you can do the following:

for option in parser.option_list:
    if option.default != ("NO", "DEFAULT"): += (" " if else "") + "[default: %default]"

And if you need programmatic access to the default values, you can get to them via the defaults attribute of the parser (it’s a dict)

The comments to your question already indicate there’s another way to parse arguments called argparse. It’s been introduced in Python 3.2. It actually deprecates optparse but is used similarly.

argpass comes with different formatting classes and for instance argparse.ArgumentDefaultsHelpFormatter will also print the default values without you having to manipulate the help string manually.

ArgumentParser objects allow the help formatting to be customized by
specifying an alternate formatting class. Currently, there are four
such classes:

class argparse.RawDescriptionHelpFormatter

class argparse.RawTextHelpFormatter

class argparse.ArgumentDefaultsHelpFormatter

class argparse.MetavarTypeHelpFormatter

An example from the python docs:

>>> parser = argparse.ArgumentParser(
...     prog='PROG',
...     formatter_class=argparse.ArgumentDefaultsHelpFormatter)
>>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
>>> parser.add_argument('bar', nargs="*", default=[1, 2, 3], help='BAR!')
>>> parser.print_help()
usage: PROG [-h] [--foo FOO] [bar [bar ...]]

positional arguments:
 bar         BAR! (default: [1, 2, 3])

optional arguments:
 -h, --help  show this help message and exit
 --foo FOO   FOO! (default: 42)

see argparse formatting classes

Add argparse.ArgumentDefaultsHelpFormatter to your parser

    import argparse

    parser = argparse.ArgumentParser(
    description='Your application description',

from documentation:

ArgumentDefaultsHelpFormatter automatically adds information about
default values to each of the argument help messages: