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=1makes the option anint, so--count abcis rejected with a clear error. You can also settype=int,float,stror richer types. - Required options:
required=True. Without a default and not required, the value isNonewhen omitted. - Boolean flags:
is_flag=Truemakes--verbosea switch that isTruewhen present. On/off pairs are written"--color/--no-color". - Counting:
count=Truecounts repetitions, so-vvvgives 3, a classic verbosity pattern. - Multiple values:
multiple=Truecollects--tag a --tag binto a tuple;nargs=2takes two values per occurrence. - Help:
help="..."text appears in--help, andshow_default=Truedisplays 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.