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 ofhelp_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
Groupand the options of aCommand, lowest first. Anything the author did not number sits on this line, so a lone{"prep": 1}promotesprepwithout displacing the rest, and a number above100demotes.Note
Priorities are floats, not integers, so a new entry can be wedged between two existing ones without renumbering:
1.5lands between1and2.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 from1.01to31.99. BASIC numbered lines with plain integers, and its10, 20, 30convention 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:
OptionGroupAn 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, whichCommandreads the same way to push click-extra’s own options to the end ofparams.- Parameters:
priority (
float) – rank of the group among the other trailing groups, lowest first. Defaults toDEFAULT_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
OptionGroupsacts 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
hiddenparameter.
- 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
ExtraOptionGroupcarries as a priority so it survives the reshufflingCommanddoes toparams.The last section gathers the options that replace the run instead of configuring it: each one prints and exits.
--timeis 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
--configends it too when a file fails to load, and would be misfiled.-h/--helpis 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
@commandand@group.- Parameters:
screen (
VersionScreen|None) –a
VersionScreenfor--versionto draw in place of its one-line message. Reach it through theparamshook, binding the screen withfunctools.partialso each decorated command still gets its own fresh option instances:@group(params=partial(default_params, screen=MY_SCREEN)) def cli(): pass
- Return type:
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).
--time/--no-timeHint
--timeis placed at the top of all other eager options so all other options’ processing time can be measured.
--config LOCATIONHint
--configis at the top so it can have a direct influence on the default behavior and value of the other options.
--no-config--validate-config LOCATION--export-config FORMAT--accessibleHint
--accessibleis placed before--colorand--table-formatso it can lower their defaults (viadefault_map) before they are resolved.
--color/--no-color--progress/--no-progress--theme--params--table-format FORMAT--verbosity LEVEL-v,--verbose-q,--quiet--debug--tree--man--help-format FORMAT--version-h,--helpAttention
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_prioritiesargument of@commandand@groupreshuffles without touching a single callback. Seeparam_priority()and click_extra#544 issue.Presentation also sorts these options into the sections
DEFAULT_OPTION_GROUPSdeclares, drawn after the command’s own options. The two orders are independent:--timeis 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
getoptsemantics),Contextforcesallow_interspersed_argstoFalseso option parsing stops at the first positional argument.
- class click_extra.commands.Context(*args, meta=None, sort_subcommands=None, **kwargs)[source]¶
Bases:
ContextLike
cloup.Context, but with the ability to populate the context’smetaproperty at instantiation.Also pre-seeds
colorfor root contexts (those without a parent) from the color environment variables, so the eager help and version screens honorFORCE_COLOR,NO_COLORand their siblings (seeresolve_color_env()). With none of them set,colorstays at Click’sNonedefault, which auto-detects a TTY. Child contexts inherit the color of their parent, as Click does.When the
POSIXLY_CORRECTenvironment variable is set, this context forcesallow_interspersed_argstoFalseso option parsing stops at the first positional argument, as GNU getopt-based tools do. SeePOSIXLY_CORRECT_ENVVAR.Carries the
sort_subcommandssetting read byclick_extra.commands.Group.must_sort_subcommands(), so a whole command tree can settle its subcommand listings in one place.Todo
Propose addition of
metakeyword upstream to Click.Like parent’s context but with an extra
metakeyword-argument.Also pre-seed
colorfrom the color environment variables for a parentless context when the user did not provide it, and forceallow_interspersed_argstoFalsewhenPOSIXLY_CORRECTis set in the environment.- Parameters:
sort_subcommands (
bool|None) – whether groups list their subcommands alphabetically. Inherited from the parent context when left toNone, the way Cloup inheritsalign_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(), withtable_formatandsort_keydefaulting to the values resolved by the--table-formatand--sort-byoptions (read fromTABLE_FORMATandTABLE_SORT_KEY).ctx.metais 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:
- 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 oftable_formatandsort_keyfrom the context’s sharedmeta, delegating toclick_extra.table.print_table()(which also handles ANSI translation and colorization policy).- Return type:
- 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,CommandLike
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, likehttps://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. Seeinvoke().version_fields (
dict[str,Any] |None) – dictionary ofVersionOptiontemplate field overrides forwarded to the version option. Accepts any field fromVersionOption.template_fields(likeprog_name,version,git_branch). Lets you customize--versionoutput from the command decorator without replacing the defaultparamslist.config_strict (
bool) – forwarded to the defaultConfigOption’sstrictsetting: configuration keys not matching any CLI parameter raise an error instead of being silently ignored. Like the otherconfig_*and*_paramsforwards, it spares you from replacing the whole defaultparamslist to customize the config option.config_cascade (
bool) – forwarded to the defaultConfigOption’scascadesetting: 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 defaultConfigOption’sexcluded_paramsblocklist. Additive, unlike the option-levelexcluded_paramswhich replaces the default blocklist entirely. Items are fully-qualified parameter IDs (likemycli.mail_sources). Mutually exclusive withincluded_params.extra_keywords (
HelpKeywords|None) – aHelpKeywordsinstance whose entries are merged into the auto-collected keyword set. Use this to inject additional strings for help screen highlighting.excluded_keywords (
HelpKeywords|None) – aHelpKeywordsinstance 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 anExamples:section of the help screen, in the man page, and in every –help-format rendering. A malformed pair raisesTypeErrorhere, at command construction, rather than on the first--helpa user runs.extra_option_at_end (
bool) – reorders all parameters attached to the command, by moving all instances ofExtraOptionat 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 toDEFAULT_PRIORITY, lowest shown first. Keys are matched against each parameter’s long and short flags first, then its destination name, so the--config/--no-configpair (which shares theconfigdestination) 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 ofclickwhich 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:
auto_envvar_prefix = self.name(Click feature)Auto-generate environment variables for all options, using the command ID as prefix. The prefix is normalized to be uppercased and all non-alphanumerics replaced by underscores.
help_option_names = ("--help", "-h")(Click feature)Allow help screen to be invoked with either –help or -h options.
show_default = True(Click feature)Show all default values in help screen.
Additionally, these Cloup context settings are set:
align_option_groups = True(Cloup feature)Aligns option groups in help screen.
Every command carries the sections of
DEFAULT_OPTION_GROUPS, so leaving each to compute its own column width would step the help text left and right from one section to the next. Aligned, a command’s own options keep the column click-extra’s widest option sets, which is what thedefault_options_*_helpfixtures ofclick_extra.pytestmatch against.show_constraints = True(Cloup feature)show_subcommand_aliases = True(Cloup feature)
Click Extra also adds its own
context_settings:show_choices = None(Click Extra feature)If set to
TrueorFalse, 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 whosepromptproperty is set.Defaults to
None, which will leave all options untouched, and let them decide of their ownshow_choicessetting.show_envvar = None(Click Extra feature)If set to
TrueorFalse, 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 ownshow_envvarsetting. The rationale being that discoverability of environment variables is enabled by the--paramsoption, 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_settingsparameter:@command( context_settings={ "show_default": False, ... } )
- report_url: str | None = None¶
URL of the issue form that a bug report links to, or
Noneto report none.Set from the
report_urlconstructor argument. Declared here so the attribute exists on every command, asinvoke()reads it off the root command.
- examples: tuple[tuple[str, str], ...] = ()¶
(description, command)pairs showing the command in use.Normalized from the
examplesconstructor argument bynormalize_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 everyHelpFormatbackend) then need no guard.
- param_priority(param)[source]¶
Priority of param in the help screen.
Defaults to
DEFAULT_PRIORITY, and is otherwise resolved againstoption_prioritiesby trying each of the parameter’s flags in turn, then its destination name.Important
This orders the help screen alone. The order of
self.paramsdecides when each callback fires:click.core.iter_params_for_processingsorts 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--timeahead of everything it measures and--accessibleahead of the--colordefault 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:
- 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
ExtraOptionGroupgoes past the ungrouped section, ordered by itspriority.Important
This is the one place the section order is decided. The help screen (
format_params()), the man page and every otherHelpFormatbackend (_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--helpand 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 thehelpattribute as is. Resolution goes throughresolve_param_help()instead, the same helper the man page and every otherHelpFormatbackend reads, so an operand carries one description whatever renders it. An argument without help gets an empty string, notNone.
- format_params(ctx, formatter)[source]¶
Draw the parameter sections of the help screen.
Reimplements
cloup.OptionGroupMixin.format_paramsto honor the ordersplit_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 plainOptionsheading.- Return type:
- 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
--helpor--version).Sets the default CLI’s
prog_nameto 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 calledpython -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
rootlogger, the levels the verbosity options set, and the color the color options publish. Seeclick_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:
- invoke(ctx)[source]¶
Like parent’s
invoke, but prints theAborted!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: seereport_unexpected_error(). The innermost command catches it, as its context still holds the options of the run. Click’smain()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 thatclick-extra wrapruns.- Return type:
- make_context(info_name, args, parent=None, **extra)[source]¶
Like parent’s
make_context, but seedsctx.metawith the raw arguments.A copy of the raw, pre-parsed arguments goes under
RAW_ARGS, whichprint_params()re-parses to draw the--paramstable. A root context also records the name the CLI was invoked under, asINVOCATION_NAME.See also
See
click_extra.context.RAW_ARGSfor the full rationale and the upstream-proposal notes (related: click#1279).- Return type:
- format_examples(ctx, formatter)[source]¶
Write an
Examples:section listing the command’sexamples.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\bno-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:
- 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:
- parse_args(ctx, args)[source]¶
Like parent’s
parse_argsbut with better error messages for single-dash multi-character tokens.Also settles the presentation options before delegating, so
--color,--no-color,--accessibleand--themereach the eager help and version screens regardless of their position on the command line. See_resolve_presentation_eagerly.
- 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,CommandClick Command with help colorization but no extra params.
Mixes in
_HelpColorsMixinfor keyword highlighting and usesContextfor the colorized formatter, without inheriting fromCommand(which would injectdefault_params).Watches what its run ends on, like
Command: a patched CLI runs under Click’s ownmain(), inside thewrapcommand, 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 (viapatch_click()).
- 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,GroupClick Group with help colorization but no extra params.
Same as
ColorizedCommandbut for groups.
- 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:
_InjectedCommandSynthetic subcommand that displays help for the parent group or a subcommand.
Auto-injected into every
Group. Supports nested resolution:mycli help subgroup subcmdshows the help forsubcmdwithinsubgroup.
- class click_extra.commands.Group(*args, help_command=True, sort_subcommands=None, subcommand_priorities=None, **kwargs)[source]¶
Bases:
Command,GroupLike
cloup.Group, with sane defaults and extra help screen colorization.Like
Command.__init__, but auto-injects ahelpsubcommand.- Parameters:
help_command (
bool) – whenTrue(the default), ahelpsubcommand is automatically registered. Set toFalseto suppress it, or register your ownhelpsubcommand to override it.sort_subcommands (
bool|None) – how subcommands sharing a priority are broken apart.Truelists them alphabetically,Falsein the order they were registered.None(the default) defers to thesort_subcommandscontext setting, then toTrue. Seemust_sort_subcommands().subcommand_priorities (
Mapping[str,float] |None) – maps a subcommand name to its priority relative toDEFAULT_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
Groupbe instances ofCommand.That way all subcommands created from a
Groupbenefits 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
Groupproduce sub-groups that are also ofGrouptype.See: https://click.palletsprojects.com/en/stable/api/#click.Group.group_class
alias of
type
- 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 toTrue. This is the resolution order Cloup uses foralign_sections, and it is what lets a singlecontext_settings={"sort_subcommands": False}on the root group reach every subgroup below it instead of being repeated on each.- Return type:
- subcommand_priority(name)[source]¶
Priority of the name subcommand.
Defaults to
DEFAULT_PRIORITY.- Return type:
- listed_command(ctx, name)[source]¶
The command the help screen describes under name: the subcommand.
The extension point
LazyGroupoverrides 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.
- list_commands(ctx)[source]¶
Subcommand names in presentation order.
Sorted on
subcommand_prioritiesfirst, then broken apart bymust_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__appendshelpbefore any@cli.command()decorator runs, while acommands=[…]constructor argument lands it after, so its natural position says nothing about the author’s intent. Mirrors whatextra_option_at_enddoes to options.
- 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 overridinglist_commands()alone leaves the help screen alphabetical: the screen is rendered from sections and never calls it. Rebuild that section fromlist_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 aSectioninstance should not have it rewritten underneath them. Priorities andsort_subcommandstherefore address the default section and the flat listings (--tree, man pages, completion specs), not the contents of an explicit section.
- class click_extra.commands.LazySubcommand(import_path, section=None, fallback_to_default_section=True, short_help=None)[source]¶
Bases:
objectDeclaration 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.- 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
Sectioninstance can be shared with eagerly-registered subcommands.
- fallback_to_default_section: bool = True¶
Whether to file the subcommand under the default section when
sectionisNone.Set to
Falseto 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:
GroupA
Groupthat 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_optionin click_extra#1332 issue.lazy_subcommandsmaps command names to their import paths.Tip
lazy_subcommandsis 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
LazySubcommandinstead 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]¶
- listed_command(ctx, name)[source]¶
Like the parent, but describing a lazy subcommand not imported yet by the stand-in its
short_helpbuilds.