click_extra.commands module

        classDiagram
  ColorizedCommand <|-- _InjectedCommand
  Command <|-- ColorizedCommand
  Command <|-- Command
  Command <|-- Group
  Context <|-- Context
  Group <|-- ColorizedGroup
  Group <|-- Group
  Group <|-- LazyGroup
  OptionGroup <|-- ExtraOptionGroup
  _HelpColorsMixin <|-- ColorizedCommand
  _HelpColorsMixin <|-- ColorizedGroup
  _HelpColorsMixin <|-- Command
  _InjectedCommand <|-- HelpCommand
  _WatchedContextMixin <|-- ColorizedCommand
  _WatchedContextMixin <|-- ColorizedGroup
  _WatchedContextMixin <|-- Command
    

Wraps vanilla Click and Cloup commands with extra features.

Click Extra’s commands, groups and contexts subclass their vanilla counterparts, pre-configured with common defaults. The mixins here build custom variants.

click_extra.commands.DEFAULT_HELP_NAMES: tuple[str, ...] = ('--help', '-h')

Flags of the help option: every command’s help_option_names, and the flags of help_option().

click_extra.commands.DEFAULT_PRIORITY: Final[float] = 100.0

Implicit priority of any subcommand or option left unnumbered.

Priorities order the subcommands of a Group and the options of a Command, lowest first. Anything the author did not number sits on this line, so a lone {"prep": 1} promotes prep without displacing the rest, and a number above 100 demotes.

Note

Priorities are floats, not integers, so a new entry can be wedged between two existing ones without renumbering: 1.5 lands between 1 and 2.

That trick is as old as interactive computing. JOSS, which RAND put online in 1963, required every line number to be a pair of integers separated by a period (1.1, 10.12): a page and a line within it, jointly a step. DEC’s FOCAL carried the scheme to the PDP-8, with steps running from 1.01 to 31.99. BASIC numbered lines with plain integers, and its 10, 20, 30 convention is programmers buying back the same insertion room by hand.

click_extra.commands.EXTRA_OPTION_SETTINGS: tuple[str, ...] = ('show_choices', 'show_envvar')

Click Extra context settings forced onto every option when set to non-None.

class click_extra.commands.ExtraOptionGroup(*args, priority=100.0, **kwargs)[source]

Bases: OptionGroup

An option group Click Extra draws after the command’s own options.

Cloup lays a help screen out as the explicit option groups first and the ungrouped options last. Click Extra injects a score of its own options into every command, so grouping them under that rule would push the author’s own options below click-extra’s and retitle them Other options. split_option_groups() sends a group carrying this marker past the ungrouped section instead.

Note

The marker mirrors ExtraOption, which Command reads the same way to push click-extra’s own options to the end of params.

Parameters:

priority (float) – rank of the group among the other trailing groups, lowest first. Defaults to DEFAULT_PRIORITY, so a group a CLI author marks this way lands after click-extra’s own.

Contains the information of an option group and identifies it. Note that, as far as the clients of this library are concerned, an OptionGroups acts as a “marker” for options, not as a container for related options. When you call @optgroup.option(...) you are not adding an option to a container, you are just adding an option marked with this option group.

Added in version 0.8.0: The hidden parameter.

click_extra.commands.DEFAULT_OPTION_GROUPS: Final[tuple[tuple[str, tuple[str, ...]], ...]] = (('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')))

Sections default_params() sorts its options into, in rendering order.

Each entry pairs a help-screen heading with the primary flags it collects. The sequence is the order the sections are drawn in, which ExtraOptionGroup carries as a priority so it survives the reshuffling Command does to params.

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

Caution

Membership is declared, not inferred. Deriving it from the callbacks looks tempting, since each option of the last section ends the run, but --config ends it too when a file fails to load, and would be misfiled.

-h / --help is deliberately absent: Click appends it to every command on its own, so it stays ungrouped and closes the author’s own section, where a reader looks for it first.

click_extra.commands.default_params(screen=None)[source]

Default additional options added to @command and @group.

Parameters:

screen (VersionScreen | None) –

a VersionScreen for --version to draw in place of its one-line message. Reach it through the params hook, binding the screen with functools.partial so each decorated command still gets its own fresh option instances:

@group(params=partial(default_params, screen=MY_SCREEN))
def cli():
    pass

Return type:

list[Option]

Caution

The order of options has been carefully crafted to handle subtle edge-cases and avoid leaky states in unit tests.

You can still override this hard-coded order for aesthetic reasons and it should be fine. Your end-users are unlikely to be affected by these sneaky bugs, as the CLI context is going to be naturally reset after each invocation (which is not the case in unit tests).

  1. --time / --no-time

    Hint

    --time is placed at the top of all other eager options so all other options’ processing time can be measured.

  2. --config LOCATION

    Hint

    --config is at the top so it can have a direct influence on the default behavior and value of the other options.

  3. --no-config

  4. --validate-config LOCATION

  5. --export-config FORMAT

  6. --accessible

    Hint

    --accessible is placed before --color and --table-format so it can lower their defaults (via default_map) before they are resolved.

  7. --color / --no-color

  8. --progress / --no-progress

  9. --theme

  10. --params

  11. --table-format FORMAT

  12. --verbosity LEVEL

  13. -v, --verbose

  14. -q, --quiet

  15. --debug

  16. --tree

  17. --man

  18. --help-format FORMAT

  19. --version

  20. -h, --help

    Attention

    This is the option produced by the @click.decorators.help_option decorator.

    It is not explicitly referenced in the implementation of this function.

    That’s because it’s going to be added by Click itself, at the end of the list of options. By letting Click handle this, we ensure that the help option will take into account the help_option_names setting.

Note

The list above is the processing order, and it is the only one these edge-cases care about. The help screen reads a separate presentation order, which the option_priorities argument of @command and @group reshuffles without touching a single callback. See param_priority() and click_extra#544 issue.

Presentation also sorts these options into the sections DEFAULT_OPTION_GROUPS declares, drawn after the command’s own options. The two orders are independent: --time is processed first and rendered last.

click_extra.commands.POSIXLY_CORRECT_ENVVAR: Final[str] = 'POSIXLY_CORRECT'

Environment variable that requests strict POSIX argument parsing.

When this variable is present in the environment (regardless of its value, matching GNU getopt semantics), Context forces allow_interspersed_args to False so option parsing stops at the first positional argument.

class click_extra.commands.Context(*args, meta=None, sort_subcommands=None, **kwargs)[source]

Bases: Context

Like cloup.Context, but with the ability to populate the context’s meta property at instantiation.

Also pre-seeds color for root contexts (those without a parent) from the color environment variables, so the eager help and version screens honor FORCE_COLOR, NO_COLOR and their siblings (see resolve_color_env()). With none of them set, color stays at Click’s None default, which auto-detects a TTY. Child contexts inherit the color of their parent, as Click does.

When the POSIXLY_CORRECT environment variable is set, this context forces allow_interspersed_args to False so option parsing stops at the first positional argument, as GNU getopt-based tools do. See POSIXLY_CORRECT_ENVVAR.

Carries the sort_subcommands setting read by click_extra.commands.Group.must_sort_subcommands(), so a whole command tree can settle its subcommand listings in one place.

Todo

Propose addition of meta keyword upstream to Click.

Like parent’s context but with an extra meta keyword-argument.

Also pre-seed color from the color environment variables for a parentless context when the user did not provide it, and force allow_interspersed_args to False when POSIXLY_CORRECT is set in the environment.

Parameters:

sort_subcommands (bool | None) – whether groups list their subcommands alphabetically. Inherited from the parent context when left to None, the way Cloup inherits align_sections, so declaring it once on the root group settles every subgroup below it.

formatter_class

Use Click Extra’s formatter to colorize the help screen.

alias of HelpFormatter

render_table(table_data, headers=None, table_format=None, sort_key=None, **kwargs)[source]

Render a table honoring the invocation’s table options, and return it.

Same contract as click_extra.table.render_table(), with table_format and sort_key defaulting to the values resolved by the --table-format and --sort-by options (read from TABLE_FORMAT and TABLE_SORT_KEY). ctx.meta is shared along the context chain, so this works from any subcommand without reaching for the root context. Without those options in the chain, falls back to the default format and no sort.

Return type:

str

print_table(table_data, headers=None, table_format=None, sort_key=None, **kwargs)[source]

Render a table honoring the invocation’s table options, and print it.

The printing counterpart of render_table(): same defaulting of table_format and sort_key from the context’s shared meta, delegating to click_extra.table.print_table() (which also handles ANSI translation and colorization policy).

Return type:

None

class click_extra.commands.Command(*args, report_url=None, version_fields=None, config_schema=None, config_strict=False, schema_strict=False, fallback_sections=(), config_validators=(), included_params=None, excluded_params=None, config_cascade=False, extra_option_at_end=True, option_priorities=None, populate_auto_envvars=True, extra_keywords=None, excluded_keywords=None, examples=(), **kwargs)[source]

Bases: _HelpColorsMixin, _WatchedContextMixin, Command

Like cloup.command, with sane defaults and extra help screen colorization.

Like cloup.Command.__init__, with Click Extra’s defaults and parameters.

Parameters:
  • report_url (str | None) – URL of the issue form of the project, like https://github.com/orchard/harvest/issues/new. Set on the root command, an error that the CLI has no rule for then ends the run with a bug report linking to that form, instead of a bare traceback. See invoke().

  • version_fields (dict[str, Any] | None) – dictionary of VersionOption template field overrides forwarded to the version option. Accepts any field from VersionOption.template_fields (like prog_name, version, git_branch). Lets you customize --version output from the command decorator without replacing the default params list.

  • config_strict (bool) – forwarded to the default ConfigOption’s strict setting: configuration keys not matching any CLI parameter raise an error instead of being silently ignored. Like the other config_* and *_params forwards, it spares you from replacing the whole default params list to customize the config option.

  • config_cascade (bool) – forwarded to the default ConfigOption’s cascade setting: auto-discovery layers every configuration file it finds, the most local one winning on key lookup, instead of stopping at the first.

  • excluded_params (Sequence[str] | None) – additional parameter IDs to block from configuration files, merged into the default ConfigOption’s excluded_params blocklist. Additive, unlike the option-level excluded_params which replaces the default blocklist entirely. Items are fully-qualified parameter IDs (like mycli.mail_sources). Mutually exclusive with included_params.

  • extra_keywords (HelpKeywords | None) – a HelpKeywords instance whose entries are merged into the auto-collected keyword set. Use this to inject additional strings for help screen highlighting.

  • excluded_keywords (HelpKeywords | None) – a HelpKeywords instance whose entries are removed from the auto-collected keyword set. Use this to suppress highlighting of specific strings.

  • examples (Sequence[Sequence[str]]) – a sequence of (description, command) string pairs showing the command in use. They are rendered in an Examples: section of the help screen, in the man page, and in every –help-format rendering. A malformed pair raises TypeError here, at command construction, rather than on the first --help a user runs.

  • extra_option_at_end (bool) – reorders all parameters attached to the command, by moving all instances of ExtraOption at the end of the parameter list. The original order of the options is preserved among themselves.

  • option_priorities (Mapping[str, float] | None) – maps an option to its priority in the help screen, relative to DEFAULT_PRIORITY, lowest shown first. Keys are matched against each parameter’s long and short flags first, then its destination name, so the --config / --no-config pair (which shares the config destination) stays addressable one flag at a time. Presentation only: self.params, and with it the order callbacks are evaluated in, is left alone. Positional arguments are never reordered, their sequence being part of the command’s grammar.

  • populate_auto_envvars (bool) – forces all parameters to have their auto-generated environment variables registered. This addresses the shortcoming of click which only evaluates them dynamically. Once registered, the auto-generated environment variables get displayed in the help screen, fixing click#2483 issue. On Windows, environment variable names are case-insensitive, so they are normalized to uppercase.

By default, these Click context settings are applied:

Additionally, these Cloup context settings are set:

Click Extra also adds its own context_settings:

  • show_choices = None (Click Extra feature)

    If set to True or False, will force that value on all options, so we can globally show or hide choices when prompting a user for input. Only makes sense for options whose prompt property is set.

    Defaults to None, which will leave all options untouched, and let them decide of their own show_choices setting.

  • show_envvar = None (Click Extra feature)

    If set to True or False, will force that value on all options, so we can globally enable or disable the display of environment variables in help screen.

    Defaults to None, which will leave all options untouched, and let them decide of their own show_envvar setting. The rationale being that discoverability of environment variables is enabled by the --params option, which is active by default on extra commands. So there is no need to surcharge the help screen.

    This addresses the click#2313 issue.

To override these defaults, you can pass your own settings with the context_settings parameter:

@command(
    context_settings={
        "show_default": False,
        ...
    }
)
context_class

alias of Context

report_url: str | None = None

URL of the issue form that a bug report links to, or None to report none.

Set from the report_url constructor argument. Declared here so the attribute exists on every command, as invoke() reads it off the root command.

examples: tuple[tuple[str, str], ...] = ()

(description, command) pairs showing the command in use.

Normalized from the examples constructor argument by normalize_examples(). Declared here so the attribute exists on every command, whether or not its author passed any: the renderers reading it (help screen, man page, and every HelpFormat backend) then need no guard.

option_priorities: dict[str, float]
context_settings: dict[str, Any]

an optional dictionary with defaults passed to the context.

param_priority(param)[source]

Priority of param in the help screen.

Defaults to DEFAULT_PRIORITY, and is otherwise resolved against option_priorities by trying each of the parameter’s flags in turn, then its destination name.

Important

This orders the help screen alone. The order of self.params decides when each callback fires: click.core.iter_params_for_processing sorts on (not is_eager, position on the command line), and every eager option the user did not type ties on that second key, leaving declaration order as the tie-break. That is what puts --time ahead of everything it measures and --accessible ahead of the --color default it lowers, so the two orders have to be free to disagree.

Positional arguments always resolve to the default: their sequence is part of the command’s grammar, not a matter of presentation.

Return type:

float

split_option_groups()[source]

Explicit option groups, split around the ungrouped section.

Hands back the groups drawn before the ungrouped options, then those drawn after. Cloup draws the ungrouped section last, with no setting to move it, which would bury a CLI’s own options under the ones Click Extra injects. So the rule is kept for the groups a CLI author declares, and every ExtraOptionGroup goes past the ungrouped section, ordered by its priority.

Important

This is the one place the section order is decided. The help screen (format_params()), the man page and every other HelpFormat backend (_build_option_groups()), and the completion specs (iter_params_for_display()) all read it, so a CLI never lists its options in one order on --help and another on --help-format man.

Return type:

tuple[tuple[OptionGroup, ...], tuple[OptionGroup, ...]]

get_argument_help_record(arg, ctx)[source]

Pair a positional argument’s metavar with its help text.

Reimplements cloup.OptionGroupMixin.get_argument_help_record, which reads the help attribute as is. Resolution goes through resolve_param_help() instead, the same helper the man page and every other HelpFormat backend reads, so an operand carries one description whatever renders it. An argument without help gets an empty string, not None.

Return type:

tuple[str, str]

format_params(ctx, formatter)[source]

Draw the parameter sections of the help screen.

Reimplements cloup.OptionGroupMixin.format_params to honor the order split_option_groups() computes, and to title the ungrouped section against the groups the CLI author declared alone. Cloup picks that title by counting every visible group, click-extra’s included, so a command carrying the default options would otherwise never show a plain Options heading.

Return type:

None

main(args=None, prog_name=None, **kwargs)[source]

Pre-invocation step that is instantiating the context, then call invoke() within it.

Caution

During context instantiation, each option’s callbacks are called. These might break the execution flow (like --help or --version).

Sets the default CLI’s prog_name to the command’s name if not provided, instead of relying on Click’s auto-detection via the _detect_program_name() method. This is to avoid the CLI being called python -m <module_name>, which is not very user-friendly.

An abort still prints Click’s Aborted!, which Click prints on purpose (pallets/click#2584), but prints it as soon as the abort leaves the command: before the close callbacks run, where Click prints it after them.

A Ctrl+C then ends the process the way an unhandled Ctrl+C does in Python: by SIGINT, once the running threads finish. Click exits with status 1 instead, which tells a calling shell the program handled the interrupt itself, so a shell loop runs on.

The process-wide state the options of Click Extra take for a run leaves with it, a run that fails while parsing included: the log handler they attach to the root logger, the levels the verbosity options set, and the color the color options publish. See click_extra.context._scoped_run.

A standard stream that cannot encode Unicode is switched to UTF-8 before anything prints, and stays so: see force_unicode_output().

Return type:

Any

invoke(ctx)[source]

Like parent’s invoke, but prints the Aborted! of an abort at once.

Click prints it once the root context has closed, so after every close callback. See _abort_notice.

Under a root command with a report_url, an error that is not one of the exceptions Click exits with ends the run with a bug report: see report_unexpected_error(). The innermost command catches it, as its context still holds the options of the run. Click’s main() also ends a run on an end of input, like an abort, and on a broken pipe, without a message: both pass through. So does any error of a run that executes the code of another project, like the CLI that click-extra wrap runs.

Return type:

Any

make_context(info_name, args, parent=None, **extra)[source]

Like parent’s make_context, but seeds ctx.meta with the raw arguments.

A copy of the raw, pre-parsed arguments goes under RAW_ARGS, which print_params() re-parses to draw the --params table. A root context also records the name the CLI was invoked under, as INVOCATION_NAME.

See also

See click_extra.context.RAW_ARGS for the full rationale and the upstream-proposal notes (related: click#1279).

Return type:

Any

format_examples(ctx, formatter)[source]

Write an Examples: section listing the command’s examples.

Each entry renders its description, then the command line it describes, indented behind a $ prompt. A command declaring none writes nothing at all, so a help screen only grows the section when it has something to put in it.

The command lines go out verbatim rather than through formatter.write_text(): an example exists to be copied, and Click’s text wrapper would fold a long one onto a second line mid-token. This is the same call the \b no-rewrap marker makes for help prose.

Nothing here styles anything. The lines land in the formatter’s buffer, which getvalue() runs through keyword highlighting on its way out, so the option names, subcommands and CLI names inside an example are painted by the same pass that paints them everywhere else.

Return type:

None

format_epilog(ctx, formatter)[source]

Insert the examples section ahead of the epilog.

Places it after the options and subcommands, which is where a reader arrives once they know what the command accepts, and keeps the author’s own epilog as the last word on the screen.

Return type:

None

parse_args(ctx, args)[source]

Like parent’s parse_args but with better error messages for single-dash multi-character tokens.

Also settles the presentation options before delegating, so --color, --no-color, --accessible and --theme reach the eager help and version screens regardless of their position on the command line. See _resolve_presentation_eagerly.

Return type:

list[str]

class click_extra.commands.ColorizedCommand(name, context_settings=None, callback=None, params=None, help=None, epilog=None, short_help=None, options_metavar='[OPTIONS]', add_help_option=True, no_args_is_help=False, hidden=False, deprecated=False)[source]

Bases: _HelpColorsMixin, _WatchedContextMixin, Command

Click Command with help colorization but no extra params.

Mixes in _HelpColorsMixin for keyword highlighting and uses Context for the colorized formatter, without inheriting from Command (which would inject default_params).

Watches what its run ends on, like Command: a patched CLI runs under Click’s own main(), inside the wrap command, and the watch is what tells that command a Ctrl+C ended its target.

Use this as a base for lightweight subcommands (like help) or for monkey-patching third-party CLIs (via patch_click()).

context_class

alias of Context

class click_extra.commands.ColorizedGroup(name=None, commands=None, invoke_without_command=False, no_args_is_help=None, subcommand_metavar=None, chain=False, result_callback=None, **kwargs)[source]

Bases: _HelpColorsMixin, _WatchedContextMixin, Group

Click Group with help colorization but no extra params.

Same as ColorizedCommand but for groups.

context_class

alias of Context

class click_extra.commands.HelpCommand(name, context_settings=None, callback=None, params=None, help=None, epilog=None, short_help=None, options_metavar='[OPTIONS]', add_help_option=True, no_args_is_help=False, hidden=False, deprecated=False)[source]

Bases: _InjectedCommand

Synthetic subcommand that displays help for the parent group or a subcommand.

Auto-injected into every Group. Supports nested resolution: mycli help subgroup subcmd shows the help for subcmd within subgroup.

invoke(ctx)[source]

Resolve the command path and display its help.

Return type:

None

class click_extra.commands.Group(*args, help_command=True, sort_subcommands=None, subcommand_priorities=None, **kwargs)[source]

Bases: Command, Group

Like cloup.Group, with sane defaults and extra help screen colorization.

Like Command.__init__, but auto-injects a help subcommand.

Parameters:
  • help_command (bool) – when True (the default), a help subcommand is automatically registered. Set to False to suppress it, or register your own help subcommand to override it.

  • sort_subcommands (bool | None) – how subcommands sharing a priority are broken apart. True lists them alphabetically, False in the order they were registered. None (the default) defers to the sort_subcommands context setting, then to True. See must_sort_subcommands().

  • subcommand_priorities (Mapping[str, float] | None) – maps a subcommand name to its priority relative to DEFAULT_PRIORITY, lowest listed first. Names left out keep the default priority, so numbering a few subcommands moves only those.

command_class

Makes commands of a Group be instances of Command.

That way all subcommands created from a Group benefits from the same defaults and extra help screen colorization.

See: https://click.palletsprojects.com/en/stable/api/#click.Group.command_class

alias of Command

group_class

Let Group produce sub-groups that are also of Group type.

See: https://click.palletsprojects.com/en/stable/api/#click.Group.group_class

alias of type

subcommand_priorities: dict[str, float]
must_sort_subcommands(ctx)[source]

Resolve whether subcommand listings are alphabetical.

Reads the group’s own sort_subcommands, then the context setting of the same name, then falls back to True. This is the resolution order Cloup uses for align_sections, and it is what lets a single context_settings={"sort_subcommands": False} on the root group reach every subgroup below it instead of being repeated on each.

Return type:

bool

subcommand_priority(name)[source]

Priority of the name subcommand.

Defaults to DEFAULT_PRIORITY.

Return type:

float

listed_command(ctx, name)[source]

The command the help screen describes under name: the subcommand.

The extension point LazyGroup overrides to describe a lazy subcommand by the help it declares, without importing it. The keyword highlighting of the help screen reads the subcommands through here.

Return type:

Command | None

list_commands(ctx)[source]

Subcommand names in presentation order.

Sorted on subcommand_priorities first, then broken apart by must_sort_subcommands(): alphabetically, or by registration order. With no priority declared every subcommand ties, leaving the tie-break as the only ordering, which is Click’s plain alphabetical listing.

In registration order the auto-injected subcommands, like help, are listed last, wherever they happen to have been registered: Group.__init__ appends help before any @cli.command() decorator runs, while a commands=[…] constructor argument lands it after, so its natural position says nothing about the author’s intent. Mirrors what extra_option_at_end does to options.

Return type:

list[str]

list_sections(ctx, include_default_section=True)[source]

Like cloup.Group.list_sections, but ordering the default section.

Cloup hard-codes the default section to Section.sorted(…), which is why overriding list_commands() alone leaves the help screen alphabetical: the screen is rendered from sections and never calls it. Rebuild that section from list_commands() instead, and hand it over already ordered.

Note

Sections the author declared themselves are returned untouched. Cloup’s own Section(is_sorted=…) already governs those, and a user holding a Section instance should not have it rewritten underneath them. Priorities and sort_subcommands therefore address the default section and the flat listings (--tree, man pages, completion specs), not the contents of an explicit section.

Return type:

list[Section]

add_command(cmd, name=None, **kwargs)[source]

Like cloup.Group.add_command, but a subcommand of the author’s replaces an auto-injected one of the same name, like the help subcommand.

Return type:

None

class click_extra.commands.LazySubcommand(import_path, section=None, fallback_to_default_section=True, short_help=None)[source]

Bases: object

Declaration of a lazily-imported subcommand of a LazyGroup.

Carries the registration settings cloup.Group.add_command() accepts, which a bare import path cannot express. A subcommand needing none of them is declared as a plain string instead.

import_path: str

Where to import the command object from, as "<module-name>.<command-name>".

section: Section | None = None

Help-screen section the subcommand is filed under, once imported.

A section declared here is registered on the group right away, so the help screen orders its sections as they are declared, not as their subcommands happen to be imported. The same Section instance can be shared with eagerly-registered subcommands.

fallback_to_default_section: bool = True

Whether to file the subcommand under the default section when section is None.

Set to False to leave the subcommand out of every section, which hides it from the help screen while keeping it invocable. Cloup calls this an escape hatch for internal code: do not disable it unless you know what you are doing.

short_help: str | None = None

The first paragraph of the subcommand’s help, for the help screen to list.

Declared, it lets the group’s help screen list the subcommand without importing it: the listing shortens it the way it shortens the help of an imported subcommand, so the line reads the same before and after the import. Left to None, drawing the help screen imports the subcommand to read its help.

class click_extra.commands.LazyGroup(*args, lazy_subcommands=None, **kwargs)[source]

Bases: Group

A Group that supports lazy loading of subcommands.

Hint

This implementation is based on the snippet from Click’s documentation: Defining the lazy group.

It has been extended to work with Click Extra’s config_option in click_extra#1332 issue.

lazy_subcommands maps command names to their import paths.

Tip

lazy_subcommands is a map of the form:

{"<command-name>": "<module-name>.<command-object-name>"}

For example:

{"mycmd": "my_cli.commands.mycmd"}

A subcommand needing registration settings on top of its import path is declared with a LazySubcommand instead of a bare string:

{"mycmd": LazySubcommand("my_cli.commands.mycmd", section=my_section)}

Every section declared that way is registered on the group here, so the help screen orders its sections as the author declared them. Waiting for each subcommand to be imported would instead order them by import, which is alphabetical and says nothing about intent.

lazy_subcommands: dict[str, LazySubcommand]
get_command(ctx, cmd_name)[source]

Get a command by name, loading lazily if necessary.

Return type:

Command | None

listed_command(ctx, name)[source]

Like the parent, but describing a lazy subcommand not imported yet by the stand-in its short_help builds.

Return type:

Command | None