Options

Click · Essentials · 11 min

Options are how users configure a command; declaring them well gives validation and help text for free.

@click.option declares an optional named parameter. The declaration names become the flags, and Click derives the Python parameter name from the longest one, converting dashes to underscores:

@click.option("-n", "--count", default=1, help="Number of greetings.")

gives your function a count argument. Key features:

  • Types from defaults. default=1 makes the option an int, so --count abc is rejected with a clear error. You can also set type=int, float, str or richer types.
  • Required options: required=True. Without a default and not required, the value is None when omitted.
  • Boolean flags: is_flag=True makes --verbose a switch that is True when present. On/off pairs are written "--color/--no-color".
  • Counting: count=True counts repetitions, so -vvv gives 3, a classic verbosity pattern.
  • Multiple values: multiple=True collects --tag a --tag b into a tuple; nargs=2 takes two values per occurrence.
  • Help: help="..." text appears in --help, and show_default=True displays the default there.

The decorator order matters only for the help listing: options appear in the order the decorators are written (top to bottom). The function receives parameters as keyword arguments, so names must match.

Options are for optional, named settings. Things the command fundamentally needs, like the file to process, are usually arguments instead.

Example

import click

@click.command()
@click.option("-n", "--count", default=1, show_default=True, help="Number of greetings.")
@click.option("--name", required=True, help="Who to greet.")
@click.option("--shout/--no-shout", default=False, help="Uppercase output.")
@click.option("-v", "--verbose", count=True, help="Repeat for more detail.")
@click.option("--tag", multiple=True, help="Tags to attach (repeatable).")
def greet(count, name, shout, verbose, tag):
    """Greet NAME a number of times."""
    msg = f"Hello, {name}!"
    for _ in range(count):
        click.echo(msg.upper() if shout else msg)
    if verbose:
        click.echo(f"verbosity={verbose} tags={tag}")

greet.main(["--name", "Ada", "-n", "2", "--shout", "-vv", "--tag", "x", "--tag", "y"],
           standalone_mode=False)
# HELLO, ADA!
# HELLO, ADA!
# verbosity=2 tags=('x', 'y')

Remember

  • @click.option('-n', '--count') maps to a count parameter
  • default= sets the type; is_flag, --x/--no-x, count and multiple cover switches and repeats
  • help= and show_default=True document options in --help

Watch out for

  • A function parameter name that doesn't match the option's derived name, causing a TypeError.

Check yourself

  1. What value does an option declared with @click.option('-v', '--verbose', count=True) receive for -vvv?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: click.palletsprojects.com/en/stable/options/