Decorators¶

If you only ever use the decorators click-extra ships out of the box, this page is not for you: @command, @group, @option and the rest work as their Click and Cloup counterparts do. It is for downstream code wiring its own @my_option decorator into the same factory.

That factory wraps cloup’s originals with three behaviors, which is what a decorator built on it inherits:

  1. Subclass-enforced cls=: every @command / @group always yields a Command / Group (or a user-supplied subclass thereof), so click-extra’s machinery (config loading, theme registry, --params introspection) can’t be silently bypassed by passing a vanilla click.Command class.

  2. Default-parameter injection: default_params() (the global option set: --time, --config, --color, --theme, …) is passed as a callable, so each command gets its own freshly-instantiated option list rather than sharing the same mutable instances.

  3. Optional-parenthesis decoration: @command and @command() are both legal call forms, matching the convention requested in Cloup #127.

decorator_factory(dec, *new_args, **new_defaults)¶

Clone a base decorator with a new set of default arguments, while validating that any user-supplied cls= is a subclass of the factory’s cls=. The result is itself a decorator that accepts the same arguments as dec and forwards them with the new defaults merged in.

The signature reads like this in click-extra’s own decorator file:

# click_extra/decorators.py
from .commands import Command, Group, default_params

command = decorator_factory(
    dec=cloup.command,
    cls=Command,
    params=default_params,
)
group = decorator_factory(
    dec=cloup.group,
    cls=Group,
    params=default_params,
)
        flowchart TD
    call(["@command / @option(...)<br/>possibly with cls=Custom"]) --> paren{"called with<br/>or without parens?"}
    paren -->|"@command"| norm["allow_missing_parenthesis<br/>normalizes both call forms"]
    paren -->|"@command()"| norm
    norm --> has{"user passed cls= ?"}
    has -->|no| build["use the factory's default cls<br/>(Command / Group / ...)"]
    has -->|yes| sub{"cls subclasses<br/>the factory's cls?"}
    sub -->|yes| build
    sub -->|no| err["raise TypeError<br/>with the full MRO listing"]
    build --> out["decorator with merged defaults<br/>and a fresh params() list"]
    

After that wiring, @command always produces a Command, and @command(cls=MyCommand) is accepted only if MyCommand is a subclass of Command. Anything else raises a TypeError with a full MRO listing of the offending class, so the caller sees why their override was rejected:

import click

from click_extra import command


# Subclass of Command: accepted.
from click_extra.commands import Command


class MyCommand(Command):
    pass


@command(cls=MyCommand)
def fine():
    pass


print(type(fine).__name__)


# Plain click.Command: rejected at decoration time.
try:

    @command(cls=click.Command)
    def bad():
        pass

except TypeError as exc:
    print(repr(exc))
MyCommand
TypeError("The 'cls' argument must be a subclass of Command, got: click.core.Command, builtins.object")

Callable params=¶

When the factory is given params= as a callable (like default_params), it’s invoked once per decorated command so each command receives a fresh list of option instances. Without this indirection, two commands declared in the same module would share the same TimerOption instance, the same ConfigOption instance, and so on, which sounds harmless but produces subtle bugs (a callback registered by one command runs again when the second command exits, the parameter source map carries stale entries, …). Pass any zero-argument callable that returns a list of click.Parameter instances.

allow_missing_parenthesis(dec_factory)¶

A small wrapper that lets a decorator-factory be called either with parentheses (the standard @dec() form) or without (@dec). decorator_factory applies it automatically to every decorator it produces.

from click_extra.decorators import allow_missing_parenthesis


def my_factory(message="default"):
    """Decorator factory: returns the decorator with a captured message."""

    def decorator(func):
        def wrapper(*args, **kwargs):
            print(message)
            return func(*args, **kwargs)

        return wrapper

    return decorator


# Without the wrapper, only `@my_factory()` (with parens) works.
flexible = allow_missing_parenthesis(my_factory)


@flexible
def a():
    pass


@flexible()
def b():
    pass


@flexible(message="hi")
def c():
    pass


a()
b()
c()
default
default
hi

The standard decorator suite¶

Every default option ships with a matching decorator. decorator_factory builds each decorator below, except the hand-written version_option and sort_by_option:

Decorator

Wraps

command

cloup.command(cls=Command, params=default_params)

group

cloup.group(cls=Group, params=default_params)

lazy_group

group(cls=LazyGroup)

multicall_group

group(cls=MulticallGroup)

option

cloup.option(cls=Option)

argument

cloup.argument(cls=Argument)

help_option

click.decorators.help_option(*DEFAULT_HELP_NAMES)

version_option

hand-written, attaches VersionOption

accessible_option

option(cls=AccessibleOption)

color_option

option(cls=ColorOption)

no_color_option

option(cls=NoColorOption)

columns_option

option(cls=ColumnsOption)

config_option

option(cls=ConfigOption)

no_config_option

option(cls=NoConfigOption)

validate_config_option

option(cls=ValidateConfigOption)

export_config_option

option(cls=ExportConfigOption)

debug_option

option(cls=DebugOption)

help_format_option

option(cls=HelpFormatOption)

jobs_option

option(cls=JobsOption)

man_option

option(cls=ManOption)

progress_option

option(cls=ProgressOption)

quiet_option

option(cls=QuietOption)

show_params_option

option(cls=ShowParamsOption)

sort_by_option

hand-written, attaches SortByOption

table_format_option

option(cls=TableFormatOption)

telemetry_option

option(cls=TelemetryOption)

theme_option

option(cls=ThemeOption)

timer_option

option(cls=TimerOption)

tree_option

option(cls=TreeOption)

verbose_option

option(cls=VerboseOption)

verbosity_option

option(cls=VerbosityOption)

zero_exit_option

option(cls=ZeroExitOption)

Every entry in this list but sort_by_option is an allow_missing_parenthesis-wrapped factory, so @theme_option and @theme_option() are both legal, and @theme_option(default="light") overrides the default while keeping the click-extra subclass guarantee. The two hand-written entries skip the factory because their leading positional argument, a version string or column definitions, conflicts with the param_decls-first convention it relies on. Neither checks that a cls= override inherits from its option class.

Each factory-built decorator also exposes the constructor signature of its option class, so editors, help() and the click_extra.decorators API page show the real parameters instead of an opaque (*args, **kwargs).

Rolling your own¶

To plug a custom ExtraOption subclass into the same machinery, instantiate decorator_factory(dec=option, cls=MyOption):

from click_extra import command, decorators, option
from click_extra.parameters import ExtraOption


class CounterOption(ExtraOption):
    """A simple ``--counter`` option with an enforced default of 0 and type int."""

    def __init__(self, *args, **kwargs):
        kwargs.setdefault("default", 0)
        kwargs.setdefault("type", int)
        super().__init__(*args, **kwargs)


counter_option = decorators.decorator_factory(
    dec=option,
    cls=CounterOption,
)


@command
@counter_option("--retries")
@counter_option("--workers")
def cli(retries, workers):
    pass


# The factory honors @counter_option (without parens) and @counter_option(...)
# (with parens) interchangeably, and produces a CounterOption instance with
# the enforced defaults applied at decoration time.
retries = next(p for p in cli.params if p.name == "retries")
workers = next(p for p in cli.params if p.name == "workers")
print(f"--retries: type={type(retries).__name__}, default={retries.default}")
print(f"--workers: type={type(workers).__name__}, default={workers.default}")
--retries: type=CounterOption, default=0
--workers: type=CounterOption, default=0

This pattern is how click-extra builds every *_option decorator listed above but the two hand-written ones, and how downstream projects can extend the suite without re-implementing the subclass-validation / fresh-params machinery.