Commands & groups

Drop-in replacement

The whole namespace of click_extra is a superset of both click and cloup namespaces. Click Extra’s main decorators, functions and classes extends and enhance Click and Cloup ones. Those left untouched by Click Extra are directly proxied to Cloup or Click.

This means if you want to upgrade an existing CLI to Click Extra, you can often replace imports of the click namespace by click_extra and it will work as expected.

Click and Cloup inheritance

At the module level, click_extra imports all elements from click.*, then all elements from the cloup.* namespace.

Which means all elements not redefined by Click Extra fallback to Cloup. And if Cloup itself does not redefine them, they fallback to Click.

For the types Click Extra does re-implement, each subclasses its Cloup counterpart, which in turn subclasses Click’s (arrows point from a child to the parent it inherits from):

        flowchart TB
    subgraph CE["click_extra (extends and overrides)"]
        direction LR
        XCmd["Command"]
        XGrp["Group"]
        XOpt["Option"]
        XArg["Argument"]
        XCtx["Context"]
        XSty["Style"]
    end
    subgraph CL["cloup (first fallback)"]
        direction LR
        CCmd["cloup.Command"]
        CGrp["cloup.Group"]
        COpt["cloup.Option"]
        CArg["cloup.Argument"]
        CCtx["cloup.Context"]
        CSty["cloup.Style"]
    end
    subgraph CK["click (base)"]
        direction LR
        KCmd["click.Command"]
        KGrp["click.Group"]
        KOpt["click.Option"]
        KArg["click.Argument"]
        KCtx["click.Context"]
        KSty["click.style()"]
    end
    XCmd --> CCmd --> KCmd
    XGrp --> CGrp --> KGrp
    XOpt --> COpt --> KOpt
    XArg --> CArg --> KArg
    XCtx --> CCtx --> KCtx
    XSty --> CSty -.->|wraps| KSty
    

For example:

  • click_extra.echo is a direct alias to click.echo because neither Click Extra or Cloup re-implements an echo helper.

  • @cloup.option_group is a specific feature of Cloup that is only implemented by it. It is not modified by Click Extra, and Click does not implement it. Still, @click_extra.option_group is a direct alias to Cloup’s one.

  • @click_extra.timer_option is a new decorator only implemented by Click Extra. So it is not a proxy of anything.

  • As for @click_extra.version_option, it is a re-implementation of @click.version_option, and so overrides it. If you want to use its original version, import it directly from click namespace.

Here is some of the main decorators of Click Extra and how they wraps and extends Cloup and Click ones:

Decorators from click_extra

Wrapped decorator

Base class

@command

@cloup.command

click_extra.Command

@group

@cloup.group

click_extra.Group

@lazy_group

@click_extra.group

click_extra.LazyGroup

@option

@cloup.option

click_extra.Option

@argument

@cloup.argument

click_extra.Argument

@version_option

-

click_extra.VersionOption

@color_option

@click_extra.option

click_extra.ColorOption

@config_option

@click_extra.option

click_extra.ConfigOption

@no_config_option

@click_extra.option

click_extra.NoConfigOption

@show_params_option

@click_extra.option

click_extra.ShowParamsOption

@table_format_option

@click_extra.option

click_extra.TableFormatOption

@telemetry_option

@click_extra.option

click_extra.TelemetryOption

@timer_option

@click_extra.option

click_extra.TimerOption

@verbose_option

@click_extra.option

click_extra.VerboseOption

@verbosity_option

@click_extra.option

click_extra.VerbosityOption

@option_group

@cloup.option_group

cloup.OptionGroup

@pass_context

@click.pass_context

-

@help_option

@click.help_option

-

…

…

…

Same for the main classes and functions, where some are re-implemented by Click Extra, and others are direct aliases to Cloup or Click ones:

Classes from click_extra

Alias to

Parent class

Command

-

cloup.Command

Group

-

cloup.Group

LazyGroup

-

click_extra.Group

Option

-

cloup.Option

Argument

-

cloup.Argument

Context

-

cloup.Context

HelpFormatter

-

cloup.HelpFormatter

HelpTheme

-

cloup.HelpTheme

CliRunner

-

click.testing.CliRunner

Result

-

click.testing.Result

VersionOption

-

click_extra.ExtraOption

Style

-

cloup.Style

echo

click.echo

ParameterSource

click.core.ParameterSource

UNSET

click._utils.UNSET

Choice

click.Choice

EnumChoice

-

click.Choice

…

…

…

Hint

You can inspect the implementation details in:

Inherited behaviors

Everything Click and Cloup do for a command still holds under Click Extra. This section shows the behaviors people most often ask about.

Streams and exit codes

Help and version screens print to stdout and exit with 0. A usage error prints to stderr, with a pointer to --help, and exits with 2. See the exit status list for the other codes.

from click_extra import command, echo, option

@command
@option("--city", help="City to forecast.")
def forecast(city):
    """Show the weather forecast."""
    echo(f"Sunny in {city}.")
$ forecast --help
Usage: forecast [OPTIONS]

  Show the weather forecast.

Options:
  --city TEXT                  City to forecast.
  -h, --help                   Show this message and exit.

Configuration options:
  --config LOCATION            Location of the configuration file. Supports
                               local path with glob patterns or remote URL.
                               [default: ~/.config/forecast/]
  --no-config                  Ignore all configuration files and only use
                               command line parameters and environment
                               variables.
  --validate-config LOCATION   Validate the configuration file and exit.
  --export-config FORMAT       Export the configuration in the selected format
                               to <stdout>, then exit.

Output options:
  --accessible                 Accessibility mode: disable colors and render
                               tables in a borderless, screen-reader-friendly
                               format.
  --color [auto|always|never]  Colorize the output. A bare --color is the same
                               as --color=always.  [default: auto]
  --no-color                   Disable colorization (alias of --color=never).
  --progress / --no-progress   Show progress indicators during long operations.
                               Disabled for non-interactive output (pipes, dumb
                               terminals, CI) and by --accessible.  [default:
                               progress]
  --theme [auto|dark|dracula|light|manpage|monokai|nord|solarized-dark]
                               Color theme used for help screens.  [default:
                               dark]
  --table-format FORMAT        Rendering style of tables.  [default: rounded-
                               outline]

Logging options:
  --verbosity LEVEL            Either CRITICAL, ERROR, WARNING, INFO, DEBUG.
                               [default: WARNING]
  -v, --verbose                Increase the default WARNING verbosity by one
                               level for each additional repetition of the
                               option.  [default: 0]
  -q, --quiet                  Decrease the default WARNING verbosity by one
                               level for each additional repetition of the
                               option.  [default: 0]
  --debug                      Shorthand for --verbosity DEBUG.

Introspection options:
  --time / --no-time           Measure and print elapsed execution time.
                               [default: no-time]
  --params                     Show all CLI parameters, their provenance,
                               defaults and value, then exit.
  --tree                       Show the tree of nested subcommands and exit.
  --man                        Read the command's manual page and exit.
  --help-format [carapace|json|json-full|man|markdown|markdown-full]
                               Render the command in the given format and exit.
  --version                    Show the version and exit.
$ forecast --city
Error: Option '--city' requires an argument.

Missing arguments

A command run without a required argument prints its usage line and a pointer to --help, then exits with 2. A group run without a subcommand prints its full help instead.

from click_extra import argument, command, echo

@command
@argument("city")
def weather(city):
    """Show the weather in CITY."""
    echo(f"Rain in {city}.")
$ weather
Usage: weather [OPTIONS] CITY
Try 'weather --help' for help.

Error: Missing argument 'CITY'.

Help epilog

The epilog argument adds text at the end of the help screen: the place for a link to the documentation or to the issue tracker.

from click_extra import command

@command(epilog="Report issues at https://example.com/orchard/issues")
def orchard():
    """Tend the orchard."""
$ orchard --help
Usage: orchard [OPTIONS]

  Tend the orchard.

Options:
  -h, --help                   Show this message and exit.

Configuration options:
  --config LOCATION            Location of the configuration file. Supports
                               local path with glob patterns or remote URL.
                               [default: ~/.config/orchard/]
  --no-config                  Ignore all configuration files and only use
                               command line parameters and environment
                               variables.
  --validate-config LOCATION   Validate the configuration file and exit.
  --export-config FORMAT       Export the configuration in the selected format
                               to <stdout>, then exit.

Output options:
  --accessible                 Accessibility mode: disable colors and render
                               tables in a borderless, screen-reader-friendly
                               format.
  --color [auto|always|never]  Colorize the output. A bare --color is the same
                               as --color=always.  [default: auto]
  --no-color                   Disable colorization (alias of --color=never).
  --progress / --no-progress   Show progress indicators during long operations.
                               Disabled for non-interactive output (pipes, dumb
                               terminals, CI) and by --accessible.  [default:
                               progress]
  --theme [auto|dark|dracula|light|manpage|monokai|nord|solarized-dark]
                               Color theme used for help screens.  [default:
                               dark]
  --table-format FORMAT        Rendering style of tables.  [default: rounded-
                               outline]

Logging options:
  --verbosity LEVEL            Either CRITICAL, ERROR, WARNING, INFO, DEBUG.
                               [default: WARNING]
  -v, --verbose                Increase the default WARNING verbosity by one
                               level for each additional repetition of the
                               option.  [default: 0]
  -q, --quiet                  Decrease the default WARNING verbosity by one
                               level for each additional repetition of the
                               option.  [default: 0]
  --debug                      Shorthand for --verbosity DEBUG.

Introspection options:
  --time / --no-time           Measure and print elapsed execution time.
                               [default: no-time]
  --params                     Show all CLI parameters, their provenance,
                               defaults and value, then exit.
  --tree                       Show the tree of nested subcommands and exit.
  --man                        Read the command's manual page and exit.
  --help-format [carapace|json|json-full|man|markdown|markdown-full]
                               Render the command in the given format and exit.
  --version                    Show the version and exit.

Report issues at https://example.com/orchard/issues

Typo suggestions

A mistyped option or subcommand gets the closest match as a suggestion.

from click_extra import argument, echo, group

@group
def garden():
    """Tend the garden."""

@garden.command(aliases=["pl"])
@argument("seed")
def plant(seed):
    """Plant a seed."""
    echo(f"Planted {seed}.")
$ garden plnat tomato
Usage: garden [OPTIONS] COMMAND [ARGS]...
Try 'garden --help' for help.

Error: No such command 'plnat'. Did you mean 'plant'?
$ forecast --cityy Paris
Usage: forecast [OPTIONS]
Try 'forecast --help' for help.

Error: No such option '--cityy'. Did you mean '--city'?

Command aliases

Cloup’s aliases give a subcommand extra names, like the pl of plant above. A prefix is not an alias: pla fails instead of running plant, so adding a subcommand never changes what an existing script runs.

$ garden pl tomato
Planted tomato.
$ garden pla tomato
Usage: garden [OPTIONS] COMMAND [ARGS]...
Try 'garden --help' for help.

Error: No such command 'pla'. (Did you mean one of: 'pl', 'plant'?)

Option position

An option belongs to the command that declares it. A group option therefore goes before the subcommand, never after it.

from click_extra import echo, group, option

@group
@option("--unit", default="celsius", help="Temperature unit.")
def station(unit):
    """Run the weather station."""

@station.command
def read():
    """Read the temperature."""
    echo("21 degrees.")
$ station --unit kelvin read
21 degrees.
$ station read --unit kelvin
Usage: station read [OPTIONS]
Try 'station read --help' for help.

Error: No such option '--unit'.

Variadic arguments

nargs=-1 lets an argument take any number of values, which also accepts what a shell glob expands to.

from click_extra import argument, command, echo

@command
@argument("fruits", nargs=-1)
def basket(fruits):
    """Fill the basket with FRUITS."""
    echo(f"{len(fruits)} fruits: {', '.join(fruits)}")
$ basket apple pear plum
3 fruits: apple, pear, plum

Prompts

prompt=True asks for a value the command line did not give. Passing the option skips the question, so a script never has to answer it.

from click_extra import command, echo, option

@command
@option("--city", prompt=True, help="City to forecast.")
def outlook(city):
    """Show the outlook."""
    echo(f"Clouds over {city}.")
$ outlook
City: Lyon
Clouds over Lyon.
$ outlook --city Nice
Clouds over Nice.

Password input

password_option asks twice for a value it does not echo.

from click_extra import command, echo, password_option

@command
@password_option()
def vault(password):
    """Open the vault."""
    echo(f"{len(password)} characters.")
$ vault
Password: 
Repeat for confirmation: 
7 characters.

Confirmation

confirmation_option asks before a dangerous action, and adds a --yes flag that skips the question.

from click_extra import command, confirmation_option, echo

@command
@confirmation_option(prompt="Delete the harvest log?")
def prune():
    """Delete the harvest log."""
    echo("Deleted.")
$ prune
Delete the harvest log? [y/N]: n
Aborted!
$ prune --yes
Deleted.

Deprecation warnings

deprecated=True on an option or a command prints a warning on stderr each time it is used.

from click_extra import command, echo, option

@command
@option("--fahrenheit", is_flag=True, deprecated=True, help="Use Fahrenheit.")
def thermometer(fahrenheit):
    """Read the thermometer."""
    echo("21 degrees.")
$ thermometer --fahrenheit
DeprecationWarning: The option '--fahrenheit' is deprecated.
21 degrees.

Default options

The @command and @group decorators are pre-configured with a set of default options. The --help/-h option is added separately through help_option_names, which is why it survives even when default_params() is reset:

Tip

Each default option publishes its resolved value on ctx.meta so you can pick it up from anywhere in your CLI. See the available keys table for the full inventory and worked examples.

Remove default options

You can remove all default options by resetting the params argument to None:

from click_extra import command

@command(params=None)
def bare_cli():
    pass

Which results in:

$ bare-cli --help
Usage: bare-cli [OPTIONS]

Options:
  -h, --help  Show this message and exit.

As you can see, all options are stripped out, but the coloring and formatting of the help message is preserved.

Change default options

To override the default options, you can provide the params= argument to the command. But note how we use classes instead of option decorators:

from click_extra import command, ConfigOption, VerbosityOption

@command(
    params=[
        ConfigOption(default="ex.yml"),
        VerbosityOption(default="DEBUG"),
    ]
)
def cli():
    pass

And now you get:

$ cli --help
Usage: cli [OPTIONS]

Options:
  --config LOCATION  Location of the configuration file. Supports local path
                     with glob patterns or remote URL.  [default: ex.yml]
  --verbosity LEVEL  Either CRITICAL, ERROR, WARNING, INFO, DEBUG.  [default:
                     DEBUG]
  -h, --help         Show this message and exit.

This let you replace the preset options by your own set, tweak their order and fine-tune their defaults.

Duplicate options

If you try to add option decorators to a command which already have them by default, you will end up with duplicate entries (as seen in issue #232):

from click_extra import command, version_option

@command
@version_option(fields={"version": "0.1"})
def cli():
    pass

See how the --version option shows up twice: once in the command’s own section, and once more where Click Extra lists its own.

$ cli --help
Usage: cli [OPTIONS]

Options:
  --version                    Show the version and exit.
  -h, --help                   Show this message and exit.

Configuration options:
  --config LOCATION            Location of the configuration file. Supports
                               local path with glob patterns or remote URL.
                               [default: ~/.config/cli/]
  --no-config                  Ignore all configuration files and only use
                               command line parameters and environment
                               variables.
  --validate-config LOCATION   Validate the configuration file and exit.
  --export-config FORMAT       Export the configuration in the selected format
                               to <stdout>, then exit.

Output options:
  --accessible                 Accessibility mode: disable colors and render
                               tables in a borderless, screen-reader-friendly
                               format.
  --color [auto|always|never]  Colorize the output. A bare --color is the same
                               as --color=always.  [default: auto]
  --no-color                   Disable colorization (alias of --color=never).
  --progress / --no-progress   Show progress indicators during long operations.
                               Disabled for non-interactive output (pipes, dumb
                               terminals, CI) and by --accessible.  [default:
                               progress]
  --theme [auto|dark|dracula|light|manpage|monokai|nord|solarized-dark]
                               Color theme used for help screens.  [default:
                               dark]
  --table-format FORMAT        Rendering style of tables.  [default: rounded-
                               outline]

Logging options:
  --verbosity LEVEL            Either CRITICAL, ERROR, WARNING, INFO, DEBUG.
                               [default: WARNING]
  -v, --verbose                Increase the default WARNING verbosity by one
                               level for each additional repetition of the
                               option.  [default: 0]
  -q, --quiet                  Decrease the default WARNING verbosity by one
                               level for each additional repetition of the
                               option.  [default: 0]
  --debug                      Shorthand for --verbosity DEBUG.

Introspection options:
  --time / --no-time           Measure and print elapsed execution time.
                               [default: no-time]
  --params                     Show all CLI parameters, their provenance,
                               defaults and value, then exit.
  --tree                       Show the tree of nested subcommands and exit.
  --man                        Read the command's manual page and exit.
  --help-format [carapace|json|json-full|man|markdown|markdown-full]
                               Render the command in the given format and exit.
  --version                    Show the version and exit.
/home/runner/work/click-extra/click-extra/click_extra/commands.py:1298: UserWarning: The parameter --version is used more than once. Remove its duplicate as parameters should be unique.
  self._resolve_presentation_eagerly(ctx, args)
/home/runner/work/click-extra/click-extra/.venv/lib/python3.14/site-packages/click/core.py:1371: UserWarning: The parameter --version is used more than once. Remove its duplicate as parameters should be unique.
  parser = self.make_parser(ctx)
/home/runner/work/click-extra/click-extra/.venv/lib/python3.14/site-packages/cloup/constraints/_support.py:188: UserWarning: The parameter --version is used more than once. Remove its duplicate as parameters should be unique.
  args = super().parse_args(ctx, args)  # type: ignore
/home/runner/work/click-extra/click-extra/click_extra/highlight.py:204: UserWarning: The parameter --version is used more than once. Remove its duplicate as parameters should be unique.
  kw.metavars.update(command.collect_usage_pieces(ctx))
/home/runner/work/click-extra/click-extra/click_extra/highlight.py:423: UserWarning: The parameter --version is used more than once. Remove its duplicate as parameters should be unique.
  formatter.keywords = self.collect_keywords(ctx)
/home/runner/work/click-extra/click-extra/.venv/lib/python3.14/site-packages/click/core.py:1164: UserWarning: The parameter --version is used more than once. Remove its duplicate as parameters should be unique.
  pieces = self.collect_usage_pieces(ctx)

This is by design: decorators are cumulative, to allow you to add your own options to the preset of @command and @group.

But notice the UserWarning log messages: The parameter --version is used more than once. Remove its duplicate as parameters should be unique.. Duplicate options are not a good practice: avoid them.

The command’s own --version sits right before -h, --help because Click appends its generated --help option at the end of the command’s own options.

Option order

Options are listed in the order they were declared: first whatever the params= argument of the decorator holds, then the option decorators stacked below @command, read bottom-up as Python applies them.

from click_extra import command, option

@command(params=[])
@option("--sugar", help="Grams of sugar.")
@option("--butter", help="Grams of butter.")
@option("--flour", help="Grams of flour.")
def bake(sugar, butter, flour):
    """Bake a cake."""
$ bake --help
Usage: bake [OPTIONS]

  Bake a cake.

Options:
  --sugar TEXT   Grams of sugar.
  --butter TEXT  Grams of butter.
  --flour TEXT   Grams of flour.
  -h, --help     Show this message and exit.

On top of that, Command moves every ExtraOption to the end of the list, so the options you wrote yourself come first and Click Extra’s own trail behind them. That is the extra_option_at_end argument, True by default:

from click_extra import VersionOption, command, option

@command(params=[VersionOption()], extra_option_at_end=False)
@option("--sugar", help="Grams of sugar.")
def keep_declared_order(sugar):
    """Bake a cake."""
$ keep-declared-order --help
Usage: keep-declared-order [OPTIONS]

  Bake a cake.

Options:
  --version     Show the version and exit.
  --sugar TEXT  Grams of sugar.
  -h, --help    Show this message and exit.

Option priorities

The order above is the processing order: it decides when each option’s callback fires, which is why --time sits ahead of everything it measures and --config ahead of the defaults it seeds. Reshuffling the help screen by hand would drag those callbacks along with it.

option_priorities moves an option on the screen alone. It maps a flag, or an option’s destination name, to a number: lowest is shown first, and anything left out sits on the DEFAULT_PRIORITY line at 100. So a number below 100 promotes, and one above demotes:

from click_extra import command, option

@command(params=[], option_priorities={"--flour": 1, "--sugar": 2, "--butter": 3})
@option("--sugar", help="Grams of sugar.")
@option("--butter", help="Grams of butter.")
@option("--flour", help="Grams of flour.")
def measured(sugar, butter, flour):
    """Bake a cake."""
$ measured --help
Usage: measured [OPTIONS]

  Bake a cake.

Options:
  --flour TEXT   Grams of flour.
  --sugar TEXT   Grams of sugar.
  --butter TEXT  Grams of butter.
  -h, --help     Show this message and exit.

The declaration order is untouched underneath:

declaration_order = [param.name for param in measured.params]
assert declaration_order == ["sugar", "butter", "flour"]
print(declaration_order)

Priorities are floats rather than integers, so a new option can be wedged between two existing ones without renumbering the rest: 1.5 lands between 1 and 2. See DEFAULT_PRIORITY for where that convention comes from.

A priority can also be written against that constant instead of against the literal 100, which reads well when a single option has to clear the crowd it was declared in:

from click_extra import command, option
from click_extra.commands import DEFAULT_PRIORITY

@command(
    params=[],
    option_priorities={
        "--flour": DEFAULT_PRIORITY - 1,
        "--sugar": DEFAULT_PRIORITY + 1,
    },
)
@option("--sugar", help="Grams of sugar.")
@option("--butter", help="Grams of butter.")
@option("--flour", help="Grams of flour.")
def relative(sugar, butter, flour):
    """Bake a cake."""

Mind the sign, as it runs against the screen: the lowest priority is listed first, so subtracting from DEFAULT_PRIORITY raises an option and adding to it lowers one. --butter was left out of the mapping and holds the default line between the two. --help is appended by Click after the sort, so it closes the command’s own section whatever the mapping says:

$ relative --help
Usage: relative [OPTIONS]

  Bake a cake.

Options:
  --flour TEXT   Grams of flour.
  --butter TEXT  Grams of butter.
  --sugar TEXT   Grams of sugar.
  -h, --help     Show this message and exit.

Positional arguments are never reordered: their sequence is part of the command’s grammar, not a matter of presentation.

Option sections

Click Extra sorts its own options into four sections, drawn after the ones a command declares:

Section

Options

Configuration options

--config, --no-config, --validate-config, --export-config

Output options

--accessible, --color, --no-color, --progress, --theme, --table-format

Logging options

--verbosity, --verbose, --quiet, --debug

Introspection options

--time, --params, --tree, --man, --help-format, --version

The last one gathers the options that replace the run instead of configuring it: each prints something and exits. --time sits there because it reports on the run rather than changing what it does.

A command’s own options keep the plain Options heading, closed by -h / --help:

from click_extra import command, option

@command
@option("--city", help="City to report on.")
def forecast(city):
    """Report a multi-day forecast."""
$ forecast --help
Usage: forecast [OPTIONS]

  Report a multi-day forecast.

Options:
  --city TEXT                  City to report on.
  -h, --help                   Show this message and exit.

Configuration options:
  --config LOCATION            Location of the configuration file. Supports
                               local path with glob patterns or remote URL.
                               [default: ~/.config/forecast/]
  --no-config                  Ignore all configuration files and only use
                               command line parameters and environment
                               variables.
  --validate-config LOCATION   Validate the configuration file and exit.
  --export-config FORMAT       Export the configuration in the selected format
                               to <stdout>, then exit.

Output options:
  --accessible                 Accessibility mode: disable colors and render
                               tables in a borderless, screen-reader-friendly
                               format.
  --color [auto|always|never]  Colorize the output. A bare --color is the same
                               as --color=always.  [default: auto]
  --no-color                   Disable colorization (alias of --color=never).
  --progress / --no-progress   Show progress indicators during long operations.
                               Disabled for non-interactive output (pipes, dumb
                               terminals, CI) and by --accessible.  [default:
                               progress]
  --theme [auto|dark|dracula|light|manpage|monokai|nord|solarized-dark]
                               Color theme used for help screens.  [default:
                               dark]
  --table-format FORMAT        Rendering style of tables.  [default: rounded-
                               outline]

Logging options:
  --verbosity LEVEL            Either CRITICAL, ERROR, WARNING, INFO, DEBUG.
                               [default: WARNING]
  -v, --verbose                Increase the default WARNING verbosity by one
                               level for each additional repetition of the
                               option.  [default: 0]
  -q, --quiet                  Decrease the default WARNING verbosity by one
                               level for each additional repetition of the
                               option.  [default: 0]
  --debug                      Shorthand for --verbosity DEBUG.

Introspection options:
  --time / --no-time           Measure and print elapsed execution time.
                               [default: no-time]
  --params                     Show all CLI parameters, their provenance,
                               defaults and value, then exit.
  --tree                       Show the tree of nested subcommands and exit.
  --man                        Read the command's manual page and exit.
  --help-format [carapace|json|json-full|man|markdown|markdown-full]
                               Render the command in the given format and exit.
  --version                    Show the version and exit.

Groups declared with @option_group come first, ahead of both. The options left ungrouped gather between them and Click Extra’s, under Cloup’s Other options heading.

To place a group of your own after Click Extra’s instead, build it with ExtraOptionGroup and give it a priority above the last section:

from click_extra import ExtraOptionGroup, command, option

@command
@option("--city", help="City to report on.")
@option(
    "--sensor",
    group=ExtraOptionGroup("Hardware options", priority=200),
    help="Identifier of the weather station.",
)
def station(city, sensor):
    """Report from a weather station."""
$ station --help
Usage: station [OPTIONS]

  Report from a weather station.

Options:
  --city TEXT                  City to report on.
  -h, --help                   Show this message and exit.

Configuration options:
  --config LOCATION            Location of the configuration file. Supports
                               local path with glob patterns or remote URL.
                               [default: ~/.config/station/]
  --no-config                  Ignore all configuration files and only use
                               command line parameters and environment
                               variables.
  --validate-config LOCATION   Validate the configuration file and exit.
  --export-config FORMAT       Export the configuration in the selected format
                               to <stdout>, then exit.

Output options:
  --accessible                 Accessibility mode: disable colors and render
                               tables in a borderless, screen-reader-friendly
                               format.
  --color [auto|always|never]  Colorize the output. A bare --color is the same
                               as --color=always.  [default: auto]
  --no-color                   Disable colorization (alias of --color=never).
  --progress / --no-progress   Show progress indicators during long operations.
                               Disabled for non-interactive output (pipes, dumb
                               terminals, CI) and by --accessible.  [default:
                               progress]
  --theme [auto|dark|dracula|light|manpage|monokai|nord|solarized-dark]
                               Color theme used for help screens.  [default:
                               dark]
  --table-format FORMAT        Rendering style of tables.  [default: rounded-
                               outline]

Logging options:
  --verbosity LEVEL            Either CRITICAL, ERROR, WARNING, INFO, DEBUG.
                               [default: WARNING]
  -v, --verbose                Increase the default WARNING verbosity by one
                               level for each additional repetition of the
                               option.  [default: 0]
  -q, --quiet                  Decrease the default WARNING verbosity by one
                               level for each additional repetition of the
                               option.  [default: 0]
  --debug                      Shorthand for --verbosity DEBUG.

Introspection options:
  --time / --no-time           Measure and print elapsed execution time.
                               [default: no-time]
  --params                     Show all CLI parameters, their provenance,
                               defaults and value, then exit.
  --tree                       Show the tree of nested subcommands and exit.
  --man                        Read the command's manual page and exit.
  --help-format [carapace|json|json-full|man|markdown|markdown-full]
                               Render the command in the given format and exit.
  --version                    Show the version and exit.

Hardware options:
  --sensor TEXT                Identifier of the weather station.

The man page and every machine-readable format read the same sections, so a CLI never lists its options one way on --help and another way elsewhere.

Option defaults

Click Extra inherits from Click, so the same override mechanisms apply.

For example, the --verbosity option defaults to the WARNING level. Now we’d like to change this default to INFO.

If you manage your own --verbosity option, you can pass the default argument to its decorator like we did above:

import click
from click_extra import verbosity_option

@click.command
@verbosity_option(default="INFO")
def cli():
    pass

This also works in its class form:

import click
from click_extra import VerbosityOption

@click.command(params=[VerbosityOption(default="INFO")])
def cli():
    pass

With a @click_extra.command instead of @click.command, it is the same, you also have the alternative to pass a default_map via the context_settings:

import click_extra

@click_extra.command(context_settings={"default_map": {"verbosity": "INFO"}})
def cli():
    pass

Which results in [default: INFO] being featured in the help message:

$ cli --help
Usage: cli [OPTIONS]

Options:
  -h, --help                   Show this message and exit.

Configuration options:
  --config LOCATION            Location of the configuration file. Supports
                               local path with glob patterns or remote URL.
                               [default: ~/.config/cli/]
  --no-config                  Ignore all configuration files and only use
                               command line parameters and environment
                               variables.
  --validate-config LOCATION   Validate the configuration file and exit.
  --export-config FORMAT       Export the configuration in the selected format
                               to <stdout>, then exit.

Output options:
  --accessible                 Accessibility mode: disable colors and render
                               tables in a borderless, screen-reader-friendly
                               format.
  --color [auto|always|never]  Colorize the output. A bare --color is the same
                               as --color=always.  [default: auto]
  --no-color                   Disable colorization (alias of --color=never).
  --progress / --no-progress   Show progress indicators during long operations.
                               Disabled for non-interactive output (pipes, dumb
                               terminals, CI) and by --accessible.  [default:
                               progress]
  --theme [auto|dark|dracula|light|manpage|monokai|nord|solarized-dark]
                               Color theme used for help screens.  [default:
                               dark]
  --table-format FORMAT        Rendering style of tables.  [default: rounded-
                               outline]

Logging options:
  --verbosity LEVEL            Either CRITICAL, ERROR, WARNING, INFO, DEBUG.
                               [default: INFO]
  -v, --verbose                Increase the default WARNING verbosity by one
                               level for each additional repetition of the
                               option.  [default: 0]
  -q, --quiet                  Decrease the default WARNING verbosity by one
                               level for each additional repetition of the
                               option.  [default: 0]
  --debug                      Shorthand for --verbosity DEBUG.

Introspection options:
  --time / --no-time           Measure and print elapsed execution time.
                               [default: no-time]
  --params                     Show all CLI parameters, their provenance,
                               defaults and value, then exit.
  --tree                       Show the tree of nested subcommands and exit.
  --man                        Read the command's manual page and exit.
  --help-format [carapace|json|json-full|man|markdown|markdown-full]
                               Render the command in the given format and exit.
  --version                    Show the version and exit.

Tip

The advantage of the context_settings method we demonstrated above, is that it let you change the default of the --verbosity option provided by Click Extra, without having to touch the params argument.

Version fields

Click’s @version_option(prog_name=...) lets you customize the name displayed by --version. But with Click Extra’s default options, the VersionOption is created for you: so there’s no decorator call to pass prog_name to.

The version_fields parameter on @command and @group solves this. It forwards values to the VersionOption in the default params list, without replacing it. It accepts any field from VersionOption.template_fields:

from click_extra import command

@command(name="my-tool", version_fields={"prog_name": "My Tool"})
def my_tool():
    """My Tool CLI."""

The name controls the usage line, while prog_name controls the --version output:

$ my-tool --help
Usage: my-tool [OPTIONS]

  My Tool CLI.

Options:
  -h, --help                   Show this message and exit.

Configuration options:
  --config LOCATION            Location of the configuration file. Supports
                               local path with glob patterns or remote URL.
                               [default: ~/.config/my-tool/]
  --no-config                  Ignore all configuration files and only use
                               command line parameters and environment
                               variables.
  --validate-config LOCATION   Validate the configuration file and exit.
  --export-config FORMAT       Export the configuration in the selected format
                               to <stdout>, then exit.

Output options:
  --accessible                 Accessibility mode: disable colors and render
                               tables in a borderless, screen-reader-friendly
                               format.
  --color [auto|always|never]  Colorize the output. A bare --color is the same
                               as --color=always.  [default: auto]
  --no-color                   Disable colorization (alias of --color=never).
  --progress / --no-progress   Show progress indicators during long operations.
                               Disabled for non-interactive output (pipes, dumb
                               terminals, CI) and by --accessible.  [default:
                               progress]
  --theme [auto|dark|dracula|light|manpage|monokai|nord|solarized-dark]
                               Color theme used for help screens.  [default:
                               dark]
  --table-format FORMAT        Rendering style of tables.  [default: rounded-
                               outline]

Logging options:
  --verbosity LEVEL            Either CRITICAL, ERROR, WARNING, INFO, DEBUG.
                               [default: WARNING]
  -v, --verbose                Increase the default WARNING verbosity by one
                               level for each additional repetition of the
                               option.  [default: 0]
  -q, --quiet                  Decrease the default WARNING verbosity by one
                               level for each additional repetition of the
                               option.  [default: 0]
  --debug                      Shorthand for --verbosity DEBUG.

Introspection options:
  --time / --no-time           Measure and print elapsed execution time.
                               [default: no-time]
  --params                     Show all CLI parameters, their provenance,
                               defaults and value, then exit.
  --tree                       Show the tree of nested subcommands and exit.
  --man                        Read the command's manual page and exit.
  --help-format [carapace|json|json-full|man|markdown|markdown-full]
                               Render the command in the given format and exit.
  --version                    Show the version and exit.
$ my-tool --version
My Tool, version None

Hint

When prog_name is not set, --version falls back to the command name, which is Click’s standard behavior.

Multiple fields can be overridden at once, including the version message template:

from click_extra import command

@command(
    version_fields={
        "prog_name": "Acme CLI",
        "version": "42.0",
        "git_branch": "release/42",
    },
)
def acme():
    pass
$ acme --version
Acme CLI, version 42.0

Examples

A command can carry usage examples, as (description, command) pairs. They render in an Examples: section of the help screen, in the man page’s EXAMPLES section, and in every machine-readable rendering:

from click_extra import command, echo, option


@command(
    examples=[
        ("Report the temperature in Fahrenheit", "forecast --units fahrenheit Oslo"),
        ("Report tomorrow's forecast", "forecast --day tomorrow Oslo"),
    ]
)
@option("--units", default="celsius", help="Temperature scale to display.")
def forecast(units):
    """Report the forecast for a city."""
    echo(f"Sunny, in {units}.")
$ forecast --help
Usage: forecast [OPTIONS]

  Report the forecast for a city.

Options:
  --units TEXT                 Temperature scale to display.  [default: celsius]
  -h, --help                   Show this message and exit.

Configuration options:
  --config LOCATION            Location of the configuration file. Supports
                               local path with glob patterns or remote URL.
                               [default: ~/.config/forecast/]
  --no-config                  Ignore all configuration files and only use
                               command line parameters and environment
                               variables.
  --validate-config LOCATION   Validate the configuration file and exit.
  --export-config FORMAT       Export the configuration in the selected format
                               to <stdout>, then exit.

Output options:
  --accessible                 Accessibility mode: disable colors and render
                               tables in a borderless, screen-reader-friendly
                               format.
  --color [auto|always|never]  Colorize the output. A bare --color is the same
                               as --color=always.  [default: auto]
  --no-color                   Disable colorization (alias of --color=never).
  --progress / --no-progress   Show progress indicators during long operations.
                               Disabled for non-interactive output (pipes, dumb
                               terminals, CI) and by --accessible.  [default:
                               progress]
  --theme [auto|dark|dracula|light|manpage|monokai|nord|solarized-dark]
                               Color theme used for help screens.  [default:
                               dark]
  --table-format FORMAT        Rendering style of tables.  [default: rounded-
                               outline]

Logging options:
  --verbosity LEVEL            Either CRITICAL, ERROR, WARNING, INFO, DEBUG.
                               [default: WARNING]
  -v, --verbose                Increase the default WARNING verbosity by one
                               level for each additional repetition of the
                               option.  [default: 0]
  -q, --quiet                  Decrease the default WARNING verbosity by one
                               level for each additional repetition of the
                               option.  [default: 0]
  --debug                      Shorthand for --verbosity DEBUG.

Introspection options:
  --time / --no-time           Measure and print elapsed execution time.
                               [default: no-time]
  --params                     Show all CLI parameters, their provenance,
                               defaults and value, then exit.
  --tree                       Show the tree of nested subcommands and exit.
  --man                        Read the command's manual page and exit.
  --help-format [carapace|json|json-full|man|markdown|markdown-full]
                               Render the command in the given format and exit.
  --version                    Show the version and exit.

Examples:
  Report the temperature in Fahrenheit:
    $ forecast --units fahrenheit Oslo

  Report tomorrow's forecast:
    $ forecast --day tomorrow Oslo

The command lines are emitted verbatim rather than wrapped: an example exists to be copied. Option names, subcommands and CLI names inside them are highlighted by the same pass that highlights them everywhere else on the screen, which is why the assertion above strips the styling before matching.

They reach the machine-readable renderings as structured entries, not as prose to be parsed back out:

$ forecast --help-format json
{
  "name": "forecast",
  "short_help": "Report the forecast for a city.",
  "version": null,
  "synopsis": "forecast [OPTIONS]",
  "description": "Report the forecast for a city.",
  "arguments": [],
  "option_groups": [
    {
      "title": "Options",
      "help": null,
      "options": [
        {
          "names": [
            "--units"
          ],
          "spec": "--units TEXT",
          "metavar": "TEXT",
          "choices": null,
          "help": "Temperature scale to display.",
          "required": false,
          "optional_value": false
        },
        {
          "names": [
            "--help",
            "-h"
          ],
          "spec": "--help / -h",
          "metavar": null,
          "choices": null,
          "help": "Show this message and exit.",
          "required": false,
          "optional_value": false
        }
      ]
    },
    {
      "title": "Configuration options",
      "help": null,
      "options": [
        {
          "names": [
            "--config"
          ],
          "spec": "--config LOCATION",
          "metavar": "LOCATION",
          "choices": null,
          "help": "Location of the configuration file. Supports local path with glob patterns or remote URL.",
          "required": false,
          "optional_value": false
        },
        {
          "names": [
            "--no-config"
          ],
          "spec": "--no-config",
          "metavar": null,
          "choices": null,
          "help": "Ignore all configuration files and only use command line parameters and environment variables.",
          "required": false,
          "optional_value": false
        },
        {
          "names": [
            "--validate-config"
          ],
          "spec": "--validate-config LOCATION",
          "metavar": "LOCATION",
          "choices": null,
          "help": "Validate the configuration file and exit.",
          "required": false,
          "optional_value": false
        },
        {
          "names": [
            "--export-config"
          ],
          "spec": "--export-config FORMAT",
          "metavar": "FORMAT",
          "choices": [
            "toml",
            "yaml",
            "json",
            "json5",
            "jsonc",
            "hjson",
            "xml",
            "plist"
          ],
          "help": "Export the configuration in the selected format to <stdout>, then exit.",
          "required": false,
          "optional_value": false
        }
      ]
    },
    {
      "title": "Output options",
      "help": null,
      "options": [
        {
          "names": [
            "--accessible"
          ],
          "spec": "--accessible",
          "metavar": null,
          "choices": null,
          "help": "Accessibility mode: disable colors and render tables in a borderless, screen-reader-friendly format.",
          "required": false,
          "optional_value": false
        },
        {
          "names": [
            "--color"
          ],
          "spec": "--color[=auto|always|never]",
          "metavar": "[auto|always|never]",
          "choices": [
            "auto",
            "always",
            "never"
          ],
          "help": "Colorize the output. A bare --color is the same as --color=always.",
          "required": false,
          "optional_value": true
        },
        {
          "names": [
            "--no-color"
          ],
          "spec": "--no-color",
          "metavar": null,
          "choices": null,
          "help": "Disable colorization (alias of --color=never).",
          "required": false,
          "optional_value": false
        },
        {
          "names": [
            "--progress",
            "--no-progress"
          ],
          "spec": "--progress / --no-progress",
          "metavar": null,
          "choices": null,
          "help": "Show progress indicators during long operations. Disabled for non-interactive output (pipes, dumb terminals, CI) and by --accessible.",
          "required": false,
          "optional_value": false
        },
        {
          "names": [
            "--theme"
          ],
          "spec": "--theme [auto|dark|dracula|light|manpage|monokai|nord|solarized-dark]",
          "metavar": "[auto|dark|dracula|light|manpage|monokai|nord|solarized-dark]",
          "choices": [
            "auto",
            "dark",
            "dracula",
            "light",
            "manpage",
            "monokai",
            "nord",
            "solarized-dark"
          ],
          "help": "Color theme used for help screens.",
          "required": false,
          "optional_value": false
        },
        {
          "names": [
            "--table-format"
          ],
          "spec": "--table-format FORMAT",
          "metavar": "FORMAT",
          "choices": [
            "aligned",
            "asciidoc",
            "colon-grid",
            "csv",
            "csv-excel",
            "csv-excel-tab",
            "csv-unix",
            "double-grid",
            "double-outline",
            "fancy-grid",
            "fancy-outline",
            "github",
            "grid",
            "heavy-grid",
            "heavy-outline",
            "hjson",
            "html",
            "jira",
            "json",
            "json5",
            "jsonc",
            "latex",
            "latex-booktabs",
            "latex-longtable",
            "latex-raw",
            "mediawiki",
            "mixed-grid",
            "mixed-outline",
            "moinmoin",
            "orgtbl",
            "outline",
            "pipe",
            "plain",
            "presto",
            "pretty",
            "psql",
            "rounded-grid",
            "rounded-outline",
            "rst",
            "simple",
            "simple-grid",
            "simple-outline",
            "textile",
            "toml",
            "tsv",
            "unsafehtml",
            "vertical",
            "xml",
            "yaml",
            "youtrack"
          ],
          "help": "Rendering style of tables.",
          "required": false,
          "optional_value": false
        }
      ]
    },
    {
      "title": "Logging options",
      "help": null,
      "options": [
        {
          "names": [
            "--verbosity"
          ],
          "spec": "--verbosity LEVEL",
          "metavar": "LEVEL",
          "choices": [
            "CRITICAL",
            "ERROR",
            "WARNING",
            "INFO",
            "DEBUG"
          ],
          "help": "Either CRITICAL, ERROR, WARNING, INFO, DEBUG.",
          "required": false,
          "optional_value": false
        },
        {
          "names": [
            "--verbose",
            "-v"
          ],
          "spec": "--verbose / -v",
          "metavar": null,
          "choices": null,
          "help": "Increase the default WARNING verbosity by one level for each additional repetition of the option.",
          "required": false,
          "optional_value": false
        },
        {
          "names": [
            "--quiet",
            "-q"
          ],
          "spec": "--quiet / -q",
          "metavar": null,
          "choices": null,
          "help": "Decrease the default WARNING verbosity by one level for each additional repetition of the option.",
          "required": false,
          "optional_value": false
        },
        {
          "names": [
            "--debug"
          ],
          "spec": "--debug",
          "metavar": null,
          "choices": null,
          "help": "Shorthand for --verbosity DEBUG.",
          "required": false,
          "optional_value": false
        }
      ]
    },
    {
      "title": "Introspection options",
      "help": null,
      "options": [
        {
          "names": [
            "--time",
            "--no-time"
          ],
          "spec": "--time / --no-time",
          "metavar": null,
          "choices": null,
          "help": "Measure and print elapsed execution time.",
          "required": false,
          "optional_value": false
        },
        {
          "names": [
            "--params"
          ],
          "spec": "--params",
          "metavar": null,
          "choices": null,
          "help": "Show all CLI parameters, their provenance, defaults and value, then exit.",
          "required": false,
          "optional_value": false
        },
        {
          "names": [
            "--tree"
          ],
          "spec": "--tree",
          "metavar": null,
          "choices": null,
          "help": "Show the tree of nested subcommands and exit.",
          "required": false,
          "optional_value": false
        },
        {
          "names": [
            "--man"
          ],
          "spec": "--man",
          "metavar": null,
          "choices": null,
          "help": "Read the command's manual page and exit.",
          "required": false,
          "optional_value": false
        },
        {
          "names": [
            "--help-format"
          ],
          "spec": "--help-format [carapace|json|json-full|man|markdown|markdown-full]",
          "metavar": "[carapace|json|json-full|man|markdown|markdown-full]",
          "choices": [
            "carapace",
            "json",
            "json-full",
            "man",
            "markdown",
            "markdown-full"
          ],
          "help": "Render the command in the given format and exit.",
          "required": false,
          "optional_value": false
        },
        {
          "names": [
            "--version"
          ],
          "spec": "--version",
          "metavar": null,
          "choices": null,
          "help": "Show the version and exit.",
          "required": false,
          "optional_value": false
        }
      ]
    }
  ],
  "subcommands": [],
  "examples": [
    {
      "description": "Report the temperature in Fahrenheit",
      "command": "forecast --units fahrenheit Oslo"
    },
    {
      "description": "Report tomorrow's forecast",
      "command": "forecast --day tomorrow Oslo"
    }
  ],
  "environment": [
    {
      "variable": "FORECAST_UNITS",
      "help": "Temperature scale to display."
    },
    {
      "variable": "FORECAST__CLICK_DEFAULT_HELP",
      "help": "Show this message and exit."
    },
    {
      "variable": "FORECAST_CONFIG",
      "help": "Location of the configuration file. Supports local path with glob patterns or remote URL."
    },
    {
      "variable": "FORECAST_VALIDATE_CONFIG",
      "help": "Validate the configuration file and exit."
    },
    {
      "variable": "FORECAST_EXPORT_CONFIG",
      "help": "Export the configuration in the selected format to <stdout>, then exit."
    },
    {
      "variable": "FORECAST_ACCESSIBLE",
      "help": "Accessibility mode: disable colors and render tables in a borderless, screen-reader-friendly format."
    },
    {
      "variable": "FORECAST_COLOR",
      "help": "Colorize the output. A bare --color is the same as --color=always."
    },
    {
      "variable": "FORECAST_NO_COLOR",
      "help": "Disable colorization (alias of --color=never)."
    },
    {
      "variable": "FORECAST_PROGRESS",
      "help": "Show progress indicators during long operations. Disabled for non-interactive output (pipes, dumb terminals, CI) and by --accessible."
    },
    {
      "variable": "FORECAST_THEME",
      "help": "Color theme used for help screens."
    },
    {
      "variable": "FORECAST_TABLE_FORMAT",
      "help": "Rendering style of tables."
    },
    {
      "variable": "FORECAST_VERBOSITY",
      "help": "Either CRITICAL, ERROR, WARNING, INFO, DEBUG."
    },
    {
      "variable": "FORECAST_VERBOSE",
      "help": "Increase the default WARNING verbosity by one level for each additional repetition of the option."
    },
    {
      "variable": "FORECAST_QUIET",
      "help": "Decrease the default WARNING verbosity by one level for each additional repetition of the option."
    },
    {
      "variable": "FORECAST_DEBUG",
      "help": "Shorthand for --verbosity DEBUG."
    },
    {
      "variable": "FORECAST_TIME",
      "help": "Measure and print elapsed execution time."
    },
    {
      "variable": "FORECAST_PARAMS",
      "help": "Show all CLI parameters, their provenance, defaults and value, then exit."
    },
    {
      "variable": "FORECAST_TREE",
      "help": "Show the tree of nested subcommands and exit."
    },
    {
      "variable": "FORECAST_MAN",
      "help": "Read the command's manual page and exit."
    },
    {
      "variable": "FORECAST_HELP_FORMAT",
      "help": "Render the command in the given format and exit."
    },
    {
      "variable": "FORECAST_VERSION",
      "help": "Show the version and exit."
    }
  ],
  "files": [
    "~/.config/forecast/{*.toml,*.yaml,*.yml,*.json,*.json5,*.jwcc,*.jsonc,*.hjson,*.ini,*.xml,*.plist,*.sqlite,*.sqlite3,*.conf,pyproject.toml}"
  ],
  "exit_status": [
    {
      "code": "0",
      "meaning": "Success."
    },
    {
      "code": "1",
      "meaning": "A runtime error, an aborted prompt (Ctrl-D), or a declined confirmation."
    },
    {
      "code": "2",
      "meaning": "A usage error: unknown option, invalid value, missing operand, or an unparsable configuration file."
    },
    {
      "code": "130",
      "meaning": "Interrupted with Ctrl-C: the process ends by SIGINT, reported as 130."
    }
  ]
}

A malformed pair raises TypeError at command construction, so a typo surfaces on import rather than on the first --help a user runs.

Subcommand order

A group lists its subcommands alphabetically, as Click does:

from click_extra import group

@group
def kitchen():
    """Run the kitchen."""

@kitchen.command()
def prep():
    """Prep the ingredients."""

@kitchen.command()
def cook():
    """Cook the dish."""

@kitchen.command()
def plate():
    """Plate the dish."""
$ kitchen --help
Usage: kitchen [OPTIONS] COMMAND [ARGS]...

  Run the kitchen.

Options:
  -h, --help                   Show this message and exit.

Configuration options:
  --config LOCATION            Location of the configuration file. Supports
                               local path with glob patterns or remote URL.
                               [default: ~/.config/kitchen/]
  --no-config                  Ignore all configuration files and only use
                               command line parameters and environment
                               variables.
  --validate-config LOCATION   Validate the configuration file and exit.
  --export-config FORMAT       Export the configuration in the selected format
                               to <stdout>, then exit.

Output options:
  --accessible                 Accessibility mode: disable colors and render
                               tables in a borderless, screen-reader-friendly
                               format.
  --color [auto|always|never]  Colorize the output. A bare --color is the same
                               as --color=always.  [default: auto]
  --no-color                   Disable colorization (alias of --color=never).
  --progress / --no-progress   Show progress indicators during long operations.
                               Disabled for non-interactive output (pipes, dumb
                               terminals, CI) and by --accessible.  [default:
                               progress]
  --theme [auto|dark|dracula|light|manpage|monokai|nord|solarized-dark]
                               Color theme used for help screens.  [default:
                               dark]
  --table-format FORMAT        Rendering style of tables.  [default: rounded-
                               outline]

Logging options:
  --verbosity LEVEL            Either CRITICAL, ERROR, WARNING, INFO, DEBUG.
                               [default: WARNING]
  -v, --verbose                Increase the default WARNING verbosity by one
                               level for each additional repetition of the
                               option.  [default: 0]
  -q, --quiet                  Decrease the default WARNING verbosity by one
                               level for each additional repetition of the
                               option.  [default: 0]
  --debug                      Shorthand for --verbosity DEBUG.

Introspection options:
  --time / --no-time           Measure and print elapsed execution time.
                               [default: no-time]
  --params                     Show all CLI parameters, their provenance,
                               defaults and value, then exit.
  --tree                       Show the tree of nested subcommands and exit.
  --man                        Read the command's manual page and exit.
  --help-format [carapace|json|json-full|man|markdown|markdown-full]
                               Render the command in the given format and exit.
  --version                    Show the version and exit.

Commands:
  cook   Cook the dish.
  help   Show help for a command.
  plate  Plate the dish.
  prep   Prep the ingredients.

Which reads well for a set of siblings, and poorly for a sequence: a kitchen preps before it cooks and cooks before it plates, and the alphabet says nothing about that.

Declaration order

sort_subcommands=False lists subcommands in the order they were registered instead:

from click_extra import group

@group(sort_subcommands=False)
def pipeline():
    """Run the kitchen."""

@pipeline.command()
def prep():
    """Prep the ingredients."""

@pipeline.command()
def cook():
    """Cook the dish."""

@pipeline.command()
def plate():
    """Plate the dish."""
$ pipeline --help
Usage: pipeline [OPTIONS] COMMAND [ARGS]...

  Run the kitchen.

Options:
  -h, --help                   Show this message and exit.

Configuration options:
  --config LOCATION            Location of the configuration file. Supports
                               local path with glob patterns or remote URL.
                               [default: ~/.config/pipeline/]
  --no-config                  Ignore all configuration files and only use
                               command line parameters and environment
                               variables.
  --validate-config LOCATION   Validate the configuration file and exit.
  --export-config FORMAT       Export the configuration in the selected format
                               to <stdout>, then exit.

Output options:
  --accessible                 Accessibility mode: disable colors and render
                               tables in a borderless, screen-reader-friendly
                               format.
  --color [auto|always|never]  Colorize the output. A bare --color is the same
                               as --color=always.  [default: auto]
  --no-color                   Disable colorization (alias of --color=never).
  --progress / --no-progress   Show progress indicators during long operations.
                               Disabled for non-interactive output (pipes, dumb
                               terminals, CI) and by --accessible.  [default:
                               progress]
  --theme [auto|dark|dracula|light|manpage|monokai|nord|solarized-dark]
                               Color theme used for help screens.  [default:
                               dark]
  --table-format FORMAT        Rendering style of tables.  [default: rounded-
                               outline]

Logging options:
  --verbosity LEVEL            Either CRITICAL, ERROR, WARNING, INFO, DEBUG.
                               [default: WARNING]
  -v, --verbose                Increase the default WARNING verbosity by one
                               level for each additional repetition of the
                               option.  [default: 0]
  -q, --quiet                  Decrease the default WARNING verbosity by one
                               level for each additional repetition of the
                               option.  [default: 0]
  --debug                      Shorthand for --verbosity DEBUG.

Introspection options:
  --time / --no-time           Measure and print elapsed execution time.
                               [default: no-time]
  --params                     Show all CLI parameters, their provenance,
                               defaults and value, then exit.
  --tree                       Show the tree of nested subcommands and exit.
  --man                        Read the command's manual page and exit.
  --help-format [carapace|json|json-full|man|markdown|markdown-full]
                               Render the command in the given format and exit.
  --version                    Show the version and exit.

Commands:
  prep   Prep the ingredients.
  cook   Cook the dish.
  plate  Plate the dish.
  help   Show help for a command.

The auto-generated help subcommand is listed last, wherever it happens to sit in the registration order, mirroring what extra_option_at_end does to options. So is the personalities subcommand of a multicall group.

Subcommand priorities

Registration order ties the listing to the shape of your source file, which is awkward when subcommands come from several modules or from a plugin scan. subcommand_priorities numbers them instead. Lowest is listed first, and any subcommand left out of the mapping sits on the DEFAULT_PRIORITY line at 100, so a number below 100 promotes and one above demotes:

from click_extra import group

@group(subcommand_priorities={"prep": 1, "plate": 2})
def numbered():
    """Run the kitchen."""

@numbered.command()
def plate():
    """Plate the dish."""

@numbered.command()
def prep():
    """Prep the ingredients."""
$ numbered --help
Usage: numbered [OPTIONS] COMMAND [ARGS]...

  Run the kitchen.

Options:
  -h, --help                   Show this message and exit.

Configuration options:
  --config LOCATION            Location of the configuration file. Supports
                               local path with glob patterns or remote URL.
                               [default: ~/.config/numbered/]
  --no-config                  Ignore all configuration files and only use
                               command line parameters and environment
                               variables.
  --validate-config LOCATION   Validate the configuration file and exit.
  --export-config FORMAT       Export the configuration in the selected format
                               to <stdout>, then exit.

Output options:
  --accessible                 Accessibility mode: disable colors and render
                               tables in a borderless, screen-reader-friendly
                               format.
  --color [auto|always|never]  Colorize the output. A bare --color is the same
                               as --color=always.  [default: auto]
  --no-color                   Disable colorization (alias of --color=never).
  --progress / --no-progress   Show progress indicators during long operations.
                               Disabled for non-interactive output (pipes, dumb
                               terminals, CI) and by --accessible.  [default:
                               progress]
  --theme [auto|dark|dracula|light|manpage|monokai|nord|solarized-dark]
                               Color theme used for help screens.  [default:
                               dark]
  --table-format FORMAT        Rendering style of tables.  [default: rounded-
                               outline]

Logging options:
  --verbosity LEVEL            Either CRITICAL, ERROR, WARNING, INFO, DEBUG.
                               [default: WARNING]
  -v, --verbose                Increase the default WARNING verbosity by one
                               level for each additional repetition of the
                               option.  [default: 0]
  -q, --quiet                  Decrease the default WARNING verbosity by one
                               level for each additional repetition of the
                               option.  [default: 0]
  --debug                      Shorthand for --verbosity DEBUG.

Introspection options:
  --time / --no-time           Measure and print elapsed execution time.
                               [default: no-time]
  --params                     Show all CLI parameters, their provenance,
                               defaults and value, then exit.
  --tree                       Show the tree of nested subcommands and exit.
  --man                        Read the command's manual page and exit.
  --help-format [carapace|json|json-full|man|markdown|markdown-full]
                               Render the command in the given format and exit.
  --version                    Show the version and exit.

Commands:
  prep   Prep the ingredients.
  plate  Plate the dish.
  help   Show help for a command.

Priorities are floats, so a subcommand added later slots between two existing ones without renumbering anything:

from click_extra import group

@group(subcommand_priorities={"prep": 1, "plate": 2, "cook": 1.5})
def wedged():
    """Run the kitchen."""

@wedged.command()
def plate():
    """Plate the dish."""

@wedged.command()
def prep():
    """Prep the ingredients."""

@wedged.command()
def cook():
    """Cook the dish."""
$ wedged --help
Usage: wedged [OPTIONS] COMMAND [ARGS]...

  Run the kitchen.

Options:
  -h, --help                   Show this message and exit.

Configuration options:
  --config LOCATION            Location of the configuration file. Supports
                               local path with glob patterns or remote URL.
                               [default: ~/.config/wedged/]
  --no-config                  Ignore all configuration files and only use
                               command line parameters and environment
                               variables.
  --validate-config LOCATION   Validate the configuration file and exit.
  --export-config FORMAT       Export the configuration in the selected format
                               to <stdout>, then exit.

Output options:
  --accessible                 Accessibility mode: disable colors and render
                               tables in a borderless, screen-reader-friendly
                               format.
  --color [auto|always|never]  Colorize the output. A bare --color is the same
                               as --color=always.  [default: auto]
  --no-color                   Disable colorization (alias of --color=never).
  --progress / --no-progress   Show progress indicators during long operations.
                               Disabled for non-interactive output (pipes, dumb
                               terminals, CI) and by --accessible.  [default:
                               progress]
  --theme [auto|dark|dracula|light|manpage|monokai|nord|solarized-dark]
                               Color theme used for help screens.  [default:
                               dark]
  --table-format FORMAT        Rendering style of tables.  [default: rounded-
                               outline]

Logging options:
  --verbosity LEVEL            Either CRITICAL, ERROR, WARNING, INFO, DEBUG.
                               [default: WARNING]
  -v, --verbose                Increase the default WARNING verbosity by one
                               level for each additional repetition of the
                               option.  [default: 0]
  -q, --quiet                  Decrease the default WARNING verbosity by one
                               level for each additional repetition of the
                               option.  [default: 0]
  --debug                      Shorthand for --verbosity DEBUG.

Introspection options:
  --time / --no-time           Measure and print elapsed execution time.
                               [default: no-time]
  --params                     Show all CLI parameters, their provenance,
                               defaults and value, then exit.
  --tree                       Show the tree of nested subcommands and exit.
  --man                        Read the command's manual page and exit.
  --help-format [carapace|json|json-full|man|markdown|markdown-full]
                               Render the command in the given format and exit.
  --version                    Show the version and exit.

Commands:
  prep   Prep the ingredients.
  cook   Cook the dish.
  plate  Plate the dish.
  help   Show help for a command.

See DEFAULT_PRIORITY for where that convention comes from.

As with options, a priority can be written against that constant rather than against the literal 100, which is enough to bookend a listing you are otherwise happy to leave alphabetical:

from click_extra import group
from click_extra.commands import DEFAULT_PRIORITY

@group(
    subcommand_priorities={
        "prep": DEFAULT_PRIORITY - 1,
        "plate": DEFAULT_PRIORITY + 1,
    },
)
def bookended():
    """Run the kitchen."""

@bookended.command()
def plate():
    """Plate the dish."""

@bookended.command()
def prep():
    """Prep the ingredients."""

@bookended.command()
def brine():
    """Brine overnight."""

@bookended.command()
def cook():
    """Cook the dish."""

The same inversion applies: subtracting lifts prep above the pack and adding drops plate below it, while brine and cook stay on the default line and keep the alphabetical tie-break between them. The help subcommand takes a priority like any other, and ties on that same line here:

$ bookended --help
Usage: bookended [OPTIONS] COMMAND [ARGS]...

  Run the kitchen.

Options:
  -h, --help                   Show this message and exit.

Configuration options:
  --config LOCATION            Location of the configuration file. Supports
                               local path with glob patterns or remote URL.
                               [default: ~/.config/bookended/]
  --no-config                  Ignore all configuration files and only use
                               command line parameters and environment
                               variables.
  --validate-config LOCATION   Validate the configuration file and exit.
  --export-config FORMAT       Export the configuration in the selected format
                               to <stdout>, then exit.

Output options:
  --accessible                 Accessibility mode: disable colors and render
                               tables in a borderless, screen-reader-friendly
                               format.
  --color [auto|always|never]  Colorize the output. A bare --color is the same
                               as --color=always.  [default: auto]
  --no-color                   Disable colorization (alias of --color=never).
  --progress / --no-progress   Show progress indicators during long operations.
                               Disabled for non-interactive output (pipes, dumb
                               terminals, CI) and by --accessible.  [default:
                               progress]
  --theme [auto|dark|dracula|light|manpage|monokai|nord|solarized-dark]
                               Color theme used for help screens.  [default:
                               dark]
  --table-format FORMAT        Rendering style of tables.  [default: rounded-
                               outline]

Logging options:
  --verbosity LEVEL            Either CRITICAL, ERROR, WARNING, INFO, DEBUG.
                               [default: WARNING]
  -v, --verbose                Increase the default WARNING verbosity by one
                               level for each additional repetition of the
                               option.  [default: 0]
  -q, --quiet                  Decrease the default WARNING verbosity by one
                               level for each additional repetition of the
                               option.  [default: 0]
  --debug                      Shorthand for --verbosity DEBUG.

Introspection options:
  --time / --no-time           Measure and print elapsed execution time.
                               [default: no-time]
  --params                     Show all CLI parameters, their provenance,
                               defaults and value, then exit.
  --tree                       Show the tree of nested subcommands and exit.
  --man                        Read the command's manual page and exit.
  --help-format [carapace|json|json-full|man|markdown|markdown-full]
                               Render the command in the given format and exit.
  --version                    Show the version and exit.

Commands:
  prep   Prep the ingredients.
  brine  Brine overnight.
  cook   Cook the dish.
  help   Show help for a command.
  plate  Plate the dish.

One setting for a whole tree

Both knobs are per-group, which means repeating them on every subgroup. sort_subcommands is also a context setting, and a context setting is inherited: declare it once on the root group and every group below it follows, unless one says otherwise.

from click_extra import group

@group(context_settings={"sort_subcommands": False})
def restaurant():
    """Run the restaurant."""

@restaurant.group()
def service():
    """Run the dining room."""

@service.command()
def seat():
    """Seat the guests."""

@service.command()
def pour():
    """Pour the wine."""
$ restaurant service --help
Usage: restaurant service [OPTIONS] COMMAND [ARGS]...

  Run the dining room.

Options:
  -h, --help  Show this message and exit.

Commands:
  seat  Seat the guests.
  pour  Pour the wine.
  help  Show help for a command.

Every rendering agrees

The order settles the help screen and every other rendering of the command tree: --tree, --help-format in all its flavors, the Carapace completion spec and shell completion all read the same listing.

$ pipeline --tree
pipeline                    Run the kitchen.
├── prep                    Prep the ingredients.
├── cook                    Cook the dish.
├── plate                   Plate the dish.
└── help [COMMAND_PATH]...  Show help for a command.

Explicit sections

Cloup’s own Section splits a long listing into titled blocks, and carries its own is_sorted flag. Priorities and sort_subcommands address the default section and the flat listings above; a section you declared yourself is left to Cloup.

help subcommand

Every Group automatically includes a help subcommand. It is the standard way to get help in most major CLIs (git, docker, cargo, npm, kubectl, gh).

mycli help shows the group’s own help, and mycli help <subcommand> shows a specific subcommand’s help:

from click_extra import echo, group, option

@group
def restaurant():
    """Restaurant management CLI."""

@restaurant.command()
@option("--city", help="City to search in.")
def find(city):
    """Find nearby restaurants."""
    echo(f"Searching in {city}...")

@restaurant.command()
@option("--stars", type=int, help="Minimum star rating.")
def rate(stars):
    """Rate a restaurant."""
    echo(f"Minimum stars: {stars}")
$ restaurant help
Usage: restaurant [OPTIONS] COMMAND [ARGS]...

  Restaurant management CLI.

Options:
  -h, --help                   Show this message and exit.

Configuration options:
  --config LOCATION            Location of the configuration file. Supports
                               local path with glob patterns or remote URL.
                               [default: ~/.config/restaurant/]
  --no-config                  Ignore all configuration files and only use
                               command line parameters and environment
                               variables.
  --validate-config LOCATION   Validate the configuration file and exit.
  --export-config FORMAT       Export the configuration in the selected format
                               to <stdout>, then exit.

Output options:
  --accessible                 Accessibility mode: disable colors and render
                               tables in a borderless, screen-reader-friendly
                               format.
  --color [auto|always|never]  Colorize the output. A bare --color is the same
                               as --color=always.  [default: auto]
  --no-color                   Disable colorization (alias of --color=never).
  --progress / --no-progress   Show progress indicators during long operations.
                               Disabled for non-interactive output (pipes, dumb
                               terminals, CI) and by --accessible.  [default:
                               progress]
  --theme [auto|dark|dracula|light|manpage|monokai|nord|solarized-dark]
                               Color theme used for help screens.  [default:
                               dark]
  --table-format FORMAT        Rendering style of tables.  [default: rounded-
                               outline]

Logging options:
  --verbosity LEVEL            Either CRITICAL, ERROR, WARNING, INFO, DEBUG.
                               [default: WARNING]
  -v, --verbose                Increase the default WARNING verbosity by one
                               level for each additional repetition of the
                               option.  [default: 0]
  -q, --quiet                  Decrease the default WARNING verbosity by one
                               level for each additional repetition of the
                               option.  [default: 0]
  --debug                      Shorthand for --verbosity DEBUG.

Introspection options:
  --time / --no-time           Measure and print elapsed execution time.
                               [default: no-time]
  --params                     Show all CLI parameters, their provenance,
                               defaults and value, then exit.
  --tree                       Show the tree of nested subcommands and exit.
  --man                        Read the command's manual page and exit.
  --help-format [carapace|json|json-full|man|markdown|markdown-full]
                               Render the command in the given format and exit.
  --version                    Show the version and exit.

Commands:
  find  Find nearby restaurants.
  help  Show help for a command.
  rate  Rate a restaurant.
$ restaurant help find
Usage: restaurant find [OPTIONS]

  Find nearby restaurants.

Options:
  --city TEXT  City to search in.
  -h, --help   Show this message and exit.

The help subcommand also supports nested groups. If mycli has a subgroup admin with a command reset, then mycli help admin reset shows the help for reset.

Searching help

The --search option searches all subcommands for matching options or descriptions:

$ restaurant help --search star
  rate: --stars  Minimum star rating.

Disabling the help subcommand

Pass help_command=False to suppress the auto-injected help subcommand:

from click_extra import group

@group(help_command=False)
def bare_cli():
    """A CLI without the help subcommand."""
$ bare-cli help
Usage: bare-cli [OPTIONS] COMMAND [ARGS]...
Try 'bare-cli --help' for help.

Error: No such command 'help'.

If you register your own help subcommand, it replaces the auto-injected one.

Lazily loading subcommands

Click Extra provides a LazyGroup class and @lazy_group decorator to create command groups that only load their subcommands when they are invoked.

This implementation is based on the one provided in Click’s documentation, so refer to the Lazily loading subcommands section for more details.

Each entry of lazy_subcommands maps a subcommand name to the import path of its command object, written as "<module-name>.<command-object-name>":

from click_extra import lazy_group

@lazy_group(lazy_subcommands={
    "apple": "produce.apple_cli",
    "banana": "produce.banana_cli",
    "carrot": "produce.carrot_cli",
})
def basket():
    """Count the produce."""

Invoking apple imports the module holding it, and leaves the other subcommands alone:

$ basket apple
apples = 3

Registration settings

A bare import path registers its subcommand with Cloup’s defaults, which files it under the default help section. Wrap the path in a LazySubcommand to carry the settings Group.add_command() accepts:

from click_extra import LazySubcommand, Section, lazy_group

fruits = Section("Fruits")
vegetables = Section("Vegetables")

@lazy_group(lazy_subcommands={
    "carrot": LazySubcommand("produce.carrot_cli", section=vegetables),
    "apple": LazySubcommand("produce.apple_cli", section=fruits),
    "banana": LazySubcommand("produce.banana_cli", section=fruits),
})
def sectioned_basket():
    """Count the produce."""

Sections show up in the order they are declared, not in the order their subcommands happen to be imported. LazyGroup registers every section as soon as it reads the declaration, so the ordering holds whatever a run imports:

$ sectioned-basket --help
Usage: sectioned-basket [OPTIONS] COMMAND [ARGS]...

  Count the produce.

Options:
  -h, --help                   Show this message and exit.

Configuration options:
  --config LOCATION            Location of the configuration file. Supports
                               local path with glob patterns or remote URL.
                               [default: ~/.config/sectioned-basket/]
  --no-config                  Ignore all configuration files and only use
                               command line parameters and environment
                               variables.
  --validate-config LOCATION   Validate the configuration file and exit.
  --export-config FORMAT       Export the configuration in the selected format
                               to <stdout>, then exit.

Output options:
  --accessible                 Accessibility mode: disable colors and render
                               tables in a borderless, screen-reader-friendly
                               format.
  --color [auto|always|never]  Colorize the output. A bare --color is the same
                               as --color=always.  [default: auto]
  --no-color                   Disable colorization (alias of --color=never).
  --progress / --no-progress   Show progress indicators during long operations.
                               Disabled for non-interactive output (pipes, dumb
                               terminals, CI) and by --accessible.  [default:
                               progress]
  --theme [auto|dark|dracula|light|manpage|monokai|nord|solarized-dark]
                               Color theme used for help screens.  [default:
                               dark]
  --table-format FORMAT        Rendering style of tables.  [default: rounded-
                               outline]

Logging options:
  --verbosity LEVEL            Either CRITICAL, ERROR, WARNING, INFO, DEBUG.
                               [default: WARNING]
  -v, --verbose                Increase the default WARNING verbosity by one
                               level for each additional repetition of the
                               option.  [default: 0]
  -q, --quiet                  Decrease the default WARNING verbosity by one
                               level for each additional repetition of the
                               option.  [default: 0]
  --debug                      Shorthand for --verbosity DEBUG.

Introspection options:
  --time / --no-time           Measure and print elapsed execution time.
                               [default: no-time]
  --params                     Show all CLI parameters, their provenance,
                               defaults and value, then exit.
  --tree                       Show the tree of nested subcommands and exit.
  --man                        Read the command's manual page and exit.
  --help-format [carapace|json|json-full|man|markdown|markdown-full]
                               Render the command in the given format and exit.
  --version                    Show the version and exit.

Vegetables:
  carrot  Count the carrots.

Fruits:
  apple   Count the apples.
  banana  Count the bananas.

Other commands:
  help    Show help for a command.

Set fallback_to_default_section=False to keep a subcommand out of every section. It disappears from the help screen, and stays invocable:

from click_extra import LazySubcommand, lazy_group

@lazy_group(lazy_subcommands={
    "apple": "produce.apple_cli",
    "carrot": LazySubcommand(
        "produce.carrot_cli", fallback_to_default_section=False
    ),
})
def stealth_basket():
    """Count the produce."""
$ stealth-basket --help
Usage: stealth-basket [OPTIONS] COMMAND [ARGS]...

  Count the produce.

Options:
  -h, --help                   Show this message and exit.

Configuration options:
  --config LOCATION            Location of the configuration file. Supports
                               local path with glob patterns or remote URL.
                               [default: ~/.config/stealth-basket/]
  --no-config                  Ignore all configuration files and only use
                               command line parameters and environment
                               variables.
  --validate-config LOCATION   Validate the configuration file and exit.
  --export-config FORMAT       Export the configuration in the selected format
                               to <stdout>, then exit.

Output options:
  --accessible                 Accessibility mode: disable colors and render
                               tables in a borderless, screen-reader-friendly
                               format.
  --color [auto|always|never]  Colorize the output. A bare --color is the same
                               as --color=always.  [default: auto]
  --no-color                   Disable colorization (alias of --color=never).
  --progress / --no-progress   Show progress indicators during long operations.
                               Disabled for non-interactive output (pipes, dumb
                               terminals, CI) and by --accessible.  [default:
                               progress]
  --theme [auto|dark|dracula|light|manpage|monokai|nord|solarized-dark]
                               Color theme used for help screens.  [default:
                               dark]
  --table-format FORMAT        Rendering style of tables.  [default: rounded-
                               outline]

Logging options:
  --verbosity LEVEL            Either CRITICAL, ERROR, WARNING, INFO, DEBUG.
                               [default: WARNING]
  -v, --verbose                Increase the default WARNING verbosity by one
                               level for each additional repetition of the
                               option.  [default: 0]
  -q, --quiet                  Decrease the default WARNING verbosity by one
                               level for each additional repetition of the
                               option.  [default: 0]
  --debug                      Shorthand for --verbosity DEBUG.

Introspection options:
  --time / --no-time           Measure and print elapsed execution time.
                               [default: no-time]
  --params                     Show all CLI parameters, their provenance,
                               defaults and value, then exit.
  --tree                       Show the tree of nested subcommands and exit.
  --man                        Read the command's manual page and exit.
  --help-format [carapace|json|json-full|man|markdown|markdown-full]
                               Render the command in the given format and exit.
  --version                    Show the version and exit.

Commands:
  apple  Count the apples.
  help   Show help for a command.
$ stealth-basket carrot
carrots = 7

Help without importing

A help screen lists every subcommand with the first paragraph of its help, so --help imports each one to read it. Declare that paragraph as the short_help of a LazySubcommand, and the help screen lists the subcommand without importing it:

from click_extra import LazySubcommand, lazy_group

@lazy_group(lazy_subcommands={
    "apple": LazySubcommand("produce.apple_cli", short_help="Count the apples."),
    "carrot": LazySubcommand("produce.carrot_cli", short_help="Count the carrots."),
})
def quick_basket():
    """Count the produce."""
$ quick-basket --help
Usage: quick-basket [OPTIONS] COMMAND [ARGS]...

  Count the produce.

Options:
  -h, --help                   Show this message and exit.

Configuration options:
  --config LOCATION            Location of the configuration file. Supports
                               local path with glob patterns or remote URL.
                               [default: ~/.config/quick-basket/]
  --no-config                  Ignore all configuration files and only use
                               command line parameters and environment
                               variables.
  --validate-config LOCATION   Validate the configuration file and exit.
  --export-config FORMAT       Export the configuration in the selected format
                               to <stdout>, then exit.

Output options:
  --accessible                 Accessibility mode: disable colors and render
                               tables in a borderless, screen-reader-friendly
                               format.
  --color [auto|always|never]  Colorize the output. A bare --color is the same
                               as --color=always.  [default: auto]
  --no-color                   Disable colorization (alias of --color=never).
  --progress / --no-progress   Show progress indicators during long operations.
                               Disabled for non-interactive output (pipes, dumb
                               terminals, CI) and by --accessible.  [default:
                               progress]
  --theme [auto|dark|dracula|light|manpage|monokai|nord|solarized-dark]
                               Color theme used for help screens.  [default:
                               dark]
  --table-format FORMAT        Rendering style of tables.  [default: rounded-
                               outline]

Logging options:
  --verbosity LEVEL            Either CRITICAL, ERROR, WARNING, INFO, DEBUG.
                               [default: WARNING]
  -v, --verbose                Increase the default WARNING verbosity by one
                               level for each additional repetition of the
                               option.  [default: 0]
  -q, --quiet                  Decrease the default WARNING verbosity by one
                               level for each additional repetition of the
                               option.  [default: 0]
  --debug                      Shorthand for --verbosity DEBUG.

Introspection options:
  --time / --no-time           Measure and print elapsed execution time.
                               [default: no-time]
  --params                     Show all CLI parameters, their provenance,
                               defaults and value, then exit.
  --tree                       Show the tree of nested subcommands and exit.
  --man                        Read the command's manual page and exit.
  --help-format [carapace|json|json-full|man|markdown|markdown-full]
                               Render the command in the given format and exit.
  --version                    Show the version and exit.

Commands:
  apple   Count the apples.
  carrot  Count the carrots.
  help    Show help for a command.

The help screen shortens the declared paragraph the way it shortens the help of an imported subcommand, so the listing reads the same before and after the import. The paragraph is a second copy of the subcommand’s own help: keep the two in step.

Lazy loading, the help screen and configuration files

A help screen prints the short help of every subcommand, so --help imports each one that declares no short_help. Lazy loading pays off on a plain mycli apple, which imports the one module carrying apple.

A configuration file also imports them all: --config matches the file against the parameters of every subcommand. An included_params allowlist limits that to the subcommands its IDs name, and included_params=() imports none of them.

Third-party commands composition

Click Extra is capable of composing with existing Click CLI in various situation.

Wrap other commands

Click builds hierarchies of commands and subcommands, and Click Extra inherits this. Third-party subcommands can be assembled into a top-level command.

Take an operation team relying daily on a couple of CLIs: dbt to manage data workflows, and aws-sam-cli to deploy them in the cloud.

To wrap all these commands into a single one:

Note

Here is how I initialized this example on my machine:

$ git clone https://github.com/kdeldycke/click-extra
(...)

$ cd click-extra
(...)

$ python -m pip install uv
(...)

$ uv venv
(...)

$ source .venv/bin/activate
(...)

$ uv sync --all-extras
(...)

$ uv pip install dbt-core
(...)

$ uv pip install aws-sam-cli
(...)

That way I had the latest Click Extra, dbt and aws-sam-cli installed in the same virtual environment:

$ uv run -- dbt --version
Core:
  - installed: 1.6.1
  - latest:    1.6.2 - Update available!

  Your version of dbt-core is out of date!
  You can find instructions for upgrading here:
  https://docs.getdbt.com/docs/installation

Plugins:
$ uv run -- sam --version
SAM CLI, version 1.97.0

Once you identified the entry points of each commands, you can easily wrap them into a top-level Click Extra CLI, here in a local script I called wrap.py:

wrap.py
import click_extra

from samcli.cli.main import cli as sam_cli
from dbt.cli.main import cli as dbt_cli


@click_extra.group(name="wrap.py")
def main():
    pass


main.add_command(cmd=sam_cli, name="aws_sam")
main.add_command(cmd=dbt_cli, name="dbt")


if __name__ == "__main__":
    main()

And this simple script gets rendered into:

$ uv run -- python ./wrap.py
Usage: wrap.py [OPTIONS] COMMAND [ARGS]...

Options:
  -h, --help                   Show this message and exit.

Configuration options:
  --config LOCATION            Location of the configuration file. Supports
                               local path with glob patterns or remote URL.
                               [default: ~/Library/Application Support/wrap.py/]
  --no-config                  Ignore all configuration files and only use
                               command line parameters and environment
                               variables.
  --validate-config LOCATION   Validate the configuration file and exit.
  --export-config FORMAT       Export the configuration in the selected format
                               to <stdout>, then exit.

Output options:
  --accessible                 Accessibility mode: disable colors and render
                               tables in a borderless, screen-reader-friendly
                               format.
  --color [auto|always|never]  Colorize the output. A bare --color is the same
                               as --color=always.  [default: auto]
  --no-color                   Disable colorization (alias of --color=never).
  --progress / --no-progress   Show progress indicators during long operations.
                               Disabled for non-interactive output (pipes, dumb
                               terminals, CI) and by --accessible.  [default:
                               progress]
  --theme [auto|dark|dracula|light|manpage|monokai|nord|solarized-dark]
                               Color theme used for help screens.  [default:
                               dark]
  --table-format FORMAT        Rendering style of tables.  [default: rounded-
                               outline]

Logging options:
  --verbosity LEVEL            Either CRITICAL, ERROR, WARNING, INFO, DEBUG.
                               [default: WARNING]
  -v, --verbose                Increase the default WARNING verbosity by one
                               level for each additional repetition of the
                               option.  [default: 0]
  -q, --quiet                  Decrease the default WARNING verbosity by one
                               level for each additional repetition of the
                               option.  [default: 0]
  --debug                      Shorthand for --verbosity DEBUG.

Introspection options:
  --time / --no-time           Measure and print elapsed execution time.
                               [default: no-time]
  --params                     Show all CLI parameters, their provenance,
                               defaults and value, then exit.
  --tree                       Show the tree of nested subcommands and exit.
  --man                        Read the command's manual page and exit.
  --help-format [carapace|json|json-full|man|markdown|markdown-full]
                               Render the command in the given format and exit.
  --version                    Show the version and exit.

Commands:
  aws_sam  AWS Serverless Application Model (SAM) CLI
  dbt      An ELT tool for managing your SQL transformations and data models.
  help     Show help for a command.

Here you can see that the top-level CLI gets all the default options and behavior (including coloring) of @group. But it also made available the standalone aws_sam and dbt CLI as standard subcommands.

And they are perfectly functional as-is.

You can compare the output of the aws_sam subcommand with its original one:

$ uv run -- python ./wrap.py aws_sam --help
Usage: wrap.py aws_sam [OPTIONS] COMMAND [ARGS]...

  AWS Serverless Application Model (SAM) CLI

  The AWS Serverless Application Model Command Line Interface (AWS SAM CLI) is
  a command line tool that you can use with AWS SAM templates and supported
  third-party integrations to build and run your serverless applications.

  Learn more: https://docs.aws.amazon.com/serverless-application-model/

Commands:

  Learn:
    docs NEW! Launch the AWS SAM CLI documentation in a browser.

  Create an App:
    init                Initialize an AWS SAM application.

  Develop your App:
    build               Build your AWS serverless function code.
    local               Run your AWS serverless function locally.
    validate            Validate an AWS SAM template.
    sync NEW! Sync an AWS SAM project to AWS.
    remote NEW! Invoke or send an event to cloud resources in your AWS
                        Cloudformation stack.

  Deploy your App:
    package             Package an AWS SAM application.
    deploy              Deploy an AWS SAM application.

  Monitor your App:
    logs                Fetch AWS Cloudwatch logs for AWS Lambda Functions or
                        Cloudwatch Log groups.
    traces              Fetch AWS X-Ray traces.

  And More:
    list NEW! Fetch the state of your AWS serverless application.
    delete              Delete an AWS SAM application and the artifacts created
                        by sam deploy.
    pipeline            Manage the continuous delivery of your AWS serverless
                        application.
    publish             Publish a packaged AWS SAM template to AWS Serverless
                        Application Repository for easy sharing.

Options:

    --beta-features / --no-beta-features
                                    Enable/Disable beta features.
    --debug                         Turn on debug logging to print debug message
                                    generated by AWS SAM CLI and display
                                    timestamps.
    --version                       Show the version and exit.
    --info                          Show system and dependencies information.
    -h, --help                      Show this message and exit.

Examples:

    Get Started:        $wrap.py aws_sam init
$ uv run -- sam --help
Usage: sam [OPTIONS] COMMAND [ARGS]...

  AWS Serverless Application Model (SAM) CLI

  The AWS Serverless Application Model Command Line Interface (AWS SAM CLI) is
  a command line tool that you can use with AWS SAM templates and supported
  third-party integrations to build and run your serverless applications.

  Learn more: https://docs.aws.amazon.com/serverless-application-model/

Commands:

  Learn:
    docs NEW! Launch the AWS SAM CLI documentation in a browser.

  Create an App:
    init                Initialize an AWS SAM application.

  Develop your App:
    build               Build your AWS serverless function code.
    local               Run your AWS serverless function locally.
    validate            Validate an AWS SAM template.
    sync NEW! Sync an AWS SAM project to AWS.
    remote NEW! Invoke or send an event to cloud resources in your AWS
                        Cloudformation stack.

  Deploy your App:
    package             Package an AWS SAM application.
    deploy              Deploy an AWS SAM application.

  Monitor your App:
    logs                Fetch AWS Cloudwatch logs for AWS Lambda Functions or
                        Cloudwatch Log groups.
    traces              Fetch AWS X-Ray traces.

  And More:
    list NEW! Fetch the state of your AWS serverless application.
    delete              Delete an AWS SAM application and the artifacts created
                        by sam deploy.
    pipeline            Manage the continuous delivery of your AWS serverless
                        application.
    publish             Publish a packaged AWS SAM template to AWS Serverless
                        Application Repository for easy sharing.

Options:

    --beta-features / --no-beta-features
                                    Enable/Disable beta features.
    --debug                         Turn on debug logging to print debug message
                                    generated by AWS SAM CLI and display
                                    timestamps.
    --version                       Show the version and exit.
    --info                          Show system and dependencies information.
    -h, --help                      Show this message and exit.

Examples:

    Get Started:        $sam init

Here is the highlighted differences to make them even more obvious:

@@ -1,5 +1,5 @@
-$ uv run -- python ./wrap.py aws_sam --help
-Usage: wrap.py aws_sam [OPTIONS] COMMAND [ARGS]...
+$ uv run -- sam --help
+Usage: sam [OPTIONS] COMMAND [ARGS]...

   AWS Serverless Application Model (SAM) CLI

@@ -56,4 +56,4 @@

 Examples:

-    Get Started:        $wrap.py aws_sam init
+    Get Started:        $sam init

Now that all commands are under the same umbrella, there is no limit to your imagination!

Caution

This might looks janky, but this franken-CLI might be a great way to solve practical problems in your situation.

The composition can carry custom glue code, simplify redistributing these CLIs on production machines, control their common dependencies, freeze their versions, hard-code parameters, apply monkey-patches, or chain commands into new automation.

If you have other examples in the same vein, share them in an issue or a PR: I’d love to complement this documentation with creative use cases.