click_extra.param_tools module¶
Helpers to introspect a CLI: its parameters and its command tree.
Every renderer of a CLI reads it through these helpers: the man pages, the
Markdown and JSON documents, the Carapace completion spec, the --tree view and
the --params table. One helper per question keeps their answers from drifting
apart: which parameters a command lists and in which order, what each one is
called, what it accepts, and how its help text reads once Click’s markers are
taken out.
- class click_extra.param_tools.P¶
Type variable bound to
click.Parameter, lettingsearch_params(),last_param()andrequire_sibling_param()return the exact subclass they were asked to find.alias of TypeVar(‘P’, bound=
Parameter)
- click_extra.param_tools.PARAM_PATH_SEP = '.'¶
Separator joining the keys of a parameter’s fully-qualified path (
cli.subcommand.param).
- click_extra.param_tools.INLINE_LITERAL_RE = re.compile('``([^`]+?)``')¶
Match a reST inline literal, text between two pairs of backticks, in a docstring.
Click stores docstrings verbatim, so any reST markup the author used to render code-like tokens in HTML docs leaks into
Command.help/Command.short_help. The roff and HTML man-page paths translate these matches into the bold/literal markers their renderers understand; the Sphinx index directive translates them intonodes.literal.
- click_extra.param_tools.iter_inline_literals(text)[source]¶
Walk
textand yield(segment, is_literal)pairs.Split on
INLINE_LITERAL_REso the consumer can apply different rendering to the literal segments (bold for roff, aliteralnode for docutils) without re-parsing the regex.
- click_extra.param_tools.clean_help(text)[source]¶
Normalize Click help prose for the backends that carry newlines natively.
Runs
inspect.cleandoc()and drops Click’s\b(\x08) no-rewrap marker, keeping every line break the marker protected. Markdown, JSON and a completion spec all represent those breaks on their own, so none needs an equivalent of the roff.nf/.fipair: only the control character has to go, or it lands in the output as a stray byte.- Return type:
- click_extra.param_tools.choice_values(param_type)[source]¶
The values a
click.Choice-like type accepts, spelled as Click completes them.An
Enummember is named by itsname, asclick.Choice.normalize_choice()does before it folds case, and anything else bystr(). A type carrying nochoicesattribute, or an empty one, answers an empty tuple. The one spelling every document of a CLI lists a choice under: the help screen, the man page, the completion spec.
- click_extra.param_tools.search_params(params, klass, include_subclasses=True)[source]¶
Return the one parameter of class
klassinparams, orNone.The result is typed as
klassitself, so a caller needs noisinstancecheck to use what it found.- Parameters:
- Raises:
RuntimeError – if more than one parameter matches.
- Return type:
- click_extra.param_tools.last_param(params, klass)[source]¶
Return the last parameter of exactly
klassinparams, orNone.Unlike
search_params(), this matches the exactklass(no subclasses) and tolerates duplicates: when an option is declared more than once (like an explicit@verbosity_optionstacked on a Click Extra command that already ships one), Click keeps the last occurrence, so this mirrors that here instead of erroring out on the ambiguity.
- click_extra.param_tools.require_sibling_param(params, requester, klass)[source]¶
Return the sibling
klassparameter declared on the same command, or raise.Some options are inert on their own: they drive machinery owned by a sibling option.
--no-configand--validate-config, for instance, both depend on the--configoption (ConfigOption). This helper centralizes the lookup so every such option raises the sameRuntimeErrorwhen its required sibling is missing, naming the offending flag.
- click_extra.param_tools.full_short_help(command)[source]¶
Return the command’s canonical one-line short help, untruncated.
Click’s
click.Command.get_short_help_str()truncates to 45 characters by default with a trailing"..."so subcommand listings fit a terminal column. That bound is wrong for generated documentation and completion specs, where the NAME / COMMANDS sections carry the full description and the renderer wraps text on its own.The lookup mirrors Click’s order: an explicit
short_helpwins, otherwise the first paragraph ofcommand.helpis joined into one line. A truthydeprecatedflag appends Click’s own label, so a listing reads the same marker Click’sget_short_help_str()produces, reason string included.- Return type:
- click_extra.param_tools.resolve_param_help(param, ctx)[source]¶
Return a parameter’s help text, including the dynamically-generated ones.
Reading
param.helpcovers the options that carry a static string, and misses the ones that compute their help from the context: Click Extra’s own-v/-qderive theirs from the resolved base verbosity, and leave the attribute atNone(seeVerboseOption.get_help_record()). Falling back to the help record picks those up.The record also carries Click’s bracket fields (
[default: …],[required],[env var: …]), appended to the prose behind two spaces. They are stripped here: they are not the author’s documentation, and every backend of this module renders them (or deliberately does not) from structured fields of its own.
- click_extra.param_tools.canonical_param_name(name)[source]¶
Fold a spelling to the parameter name Click would derive from it.
Applies Click’s own derivation, minus the option prefix its callers strip first: hyphens become underscores and the result is case-folded, so
Foo-Baranswersfoo_bar. Use it to resolve an outside spelling (a configuration key, an argfile declaration) against the names a CLI already has.Caution
The fold is many-to-one, so it identifies a name and never reconstructs a spelling.
--foo-bar,--Foo-Barand--FOO-BARanswer the same name, as do--foo--barand--foo__bar, and--K(the Kelvin sign,U+212A) lands on the samekas--k. Case folding reaches every script and is not length-preserving:--ẞanswersß, whose upper case is the two lettersSS, and a composedcaféanswers a different name than a decomposed one that renders identically.Caution
A folded spelling is a candidate, never an answer on its own. Click takes an identifier declaration verbatim, so
@option("--x", "Foo_Bar")names its parameterFoo_Bar, which this function would never produce. Match the fold against the names a CLI declares and keep the CLI’s own spelling, rather than storing what this returns.Todo
Upstream pallets/click#3827 asks whether
Optionshould keep the case of an identifier declaration, as it does today, or fold it the wayArgumentalready does. Should Click fold both, no parameter can be namedFoo_Barany more: drop the caution above, and with it the ambiguity branch of_merge_into_templateinclick_extra.config.schema, which exists only to tell two such names apart.- Return type:
- click_extra.param_tools.param_spellings(param)[source]¶
All literal spellings of a parameter: primary
optsthensecondary_opts.A boolean flag pair yields both forms (
--foo,--no-foo); a plain option yields just its declared names.
- click_extra.param_tools.short_long_opts(opts)[source]¶
Split option spellings into the first short (
-x) and long (--xy) form.Either element is the empty string when that form is absent.
- click_extra.param_tools.option_value_kind(param)[source]¶
Classify how an option consumes a value, the basis for rendering its metavar.
"flag": takes no value. A boolean switch (--foo,--foo/--no-foo), a flag with a customflag_value(--no-config), or a counter (-v)."optional": the value may be omitted. Click models this asis_flag=Falsewith aflag_valueset, so a bare--colorstands for the flag value while--color=neverpasses an explicit one."required": consumes a value (--config LOCATION).
Note
The discriminator is Click’s
is_flag(pluscount), notis_bool_flag: a flag carrying a customflag_valuesuch asNoConfigOptionreportsis_bool_flag=Falseyet still takes no value.- Return type:
Literal['flag','optional','required']
- click_extra.param_tools.resolve_flag_value(param)[source]¶
The value
param’s primary declaration stands for.Nonefor a plain option, a counter or an argument,Truefor a boolean flag, and the declared value otherwise (--colorstanding foralways).Read from Click’s
Option.flag_activation_value, not fromflag_value: Click keeps theUNSETsentinel there when no value was declared, and the sentinel stored anywhere it is read back as a value turns the flag off.- Return type:
- click_extra.param_tools.is_repeatable(param)[source]¶
Whether the parameter may be supplied several times (
multipleorcount).- Return type:
- class click_extra.param_tools.ParamStructure[source]¶
Bases:
objectUtilities to introspect CLI options and commands structure.
Structures are represented by a tree-like
dict.Access to a node is available using a serialized path string composed of the keys to descend to that node, separated by a dot
..- excluded_params: frozenset[str]¶
Fully-qualified IDs of the parameters to block from the structure.
Set by subclasses:
ShowParamsOptionfreezes an empty set, whileConfigOptionresolves a dynamic default (or the user-provided list) within the active context. The two filters are mutually exclusive, a constraint each subclass enforces in its own constructor.With an allowlist, this holds only the IDs that the walk of
build_param_trees()reaches and the allowlist leaves out. Askis_excluded()about a parameter of another subcommand.
- included_params: frozenset[str] | None¶
Allowlist of parameter IDs, mutually exclusive with
excluded_params.Nonedisables the allowlist. Otherwisebuild_param_trees()walks only the subcommands an allowed ID lies under, and resolves the parameters it reaches intoexcluded_params.
- static init_tree_dict(*path, leaf=None)[source]¶
Nest one dict per key of
path, the deepest one holdingleaf.An empty
pathreturnsleafitself.- Return type:
- static get_tree_value(tree_dict, *path)[source]¶
Get in the
tree_dictthe value located at thepath.Raises
KeyErrorif no item is found at the providedpath.- Return type:
- walk_params(*, descend=None)[source]¶
Yield every parameter of the CLI, unfiltered.
Everything is included, from top-level groups to subcommands, and from options to arguments, unless
descendskips a subcommand.Thin adapter over
walk_command_params(): it resolves the root CLI from the active context and drops the per-parameter context that the free function also yields.
- TYPE_MAP: ClassVar[dict[type[ParamType], type[str | int | float | bool | list]]] = {<class 'click.types.BoolParamType'>: <class 'bool'>, <class 'click.types.Choice'>: <class 'str'>, <class 'click.types.DateTime'>: <class 'str'>, <class 'click.types.File'>: <class 'str'>, <class 'click.types.FloatParamType'>: <class 'float'>, <class 'click.types.FloatRange'>: <class 'float'>, <class 'click.types.IntParamType'>: <class 'int'>, <class 'click.types.IntRange'>: <class 'int'>, <class 'click.types.Path'>: <class 'str'>, <class 'click.types.StringParamType'>: <class 'str'>, <class 'click.types.Tuple'>: <class 'list'>, <class 'click.types.UUIDParameterType'>: <class 'str'>, <class 'click.types.UnprocessedParamType'>: <class 'str'>}¶
Map Click types to their Python equivalent.
Keys are subclasses of
click.types.ParamType. Values are expected to be simple builtins Python types.This mapping can be seen as a reverse of the
click.types.convert_type()method.
- static map_click_type(click_type)[source]¶
Map a Click parameter type instance to its Python equivalent.
Returns
strfor unrecognised custom types, since command-line parameters are strings by default.See the list of custom types provided by Click.
- static get_param_type(param)[source]¶
Get the Python type of a Click parameter.
Returns
strfor unrecognised custom types, since command-line parameters are strings by default.A boolean flag is a
booleven when it is repeatable: it collects occurrences of a toggle rather than values, and a configuration file spells it as the boolean it is. That is why the check comes before the multi-value one, which would otherwise read it as a list and have an unset one dump as[], a shape no user writes.See the list of custom types provided by Click.
- is_excluded(param_id)[source]¶
Whether a configuration file cannot set the parameter
param_id.An allowlist answers alone: the parameter is excluded when
included_paramsdoes not name it. So the answer holds for a parameter of a subcommand that the walk ofbuild_param_trees()skipped. Without an allowlist, the parameter is excluded whenexcluded_paramslists it.- Parameters:
param_id (
str) – the fully-qualified ID of the parameter, its path keys joined withPARAM_PATH_SEP.- Return type:
- build_param_trees()[source]¶
Build and return the parameters tree structure.
Each leaf is the list of the parameters its path names: one, or several when options share a name, like the feature switches of one destination.
This removes parameters whose fully-qualified IDs are in the
excluded_paramsblocklist.With an allowlist, the tree holds only the parameters
included_paramsnames. The walk then skips each subcommand that no allowed ID lies under, so it does not import a lazy subcommand of aLazyGroupthat the allowlist leaves out. An empty allowlist walks the root command alone. The parameters the walk reaches and the allowlist leaves out becomeexcluded_params.
- click_extra.param_tools.get_param_spec(param, ctx)[source]¶
Extract the option-spec string (like
-v, --verbose) from a parameter.A hidden option has one too:
click.Option.get_help_spec()ignoreshidden. An argument has no spec, so it getsNone.
- click_extra.param_tools.make_resilient_context(command, info_name=None, parent=None)[source]¶
Build an introspection context for a command.
Parses no arguments and sets
resilient_parsing=Trueso required-argument errors, prompts and eager-option side effects stay dormant: the canonical way to materialize aclick.Contextpurely to read a command’s structure (its parameters, env-var prefix and subcommands), shared by the man-page and Carapace exporters.
- click_extra.param_tools.child_context(command, parent, info_name)[source]¶
Build the context of a subcommand under
parent, without parsing anything.Built the way
click.Command.make_context()builds one, from the command’s owncontext_classandcontext_settings, so the context reads like the one a real invocation gets: a subcommand setting its ownauto_envvar_prefixnames its environment variables after it, where a bareclick.Contextwould derive them from the parent’s prefix. Unlikemake_resilient_context(), no parameter is processed, so a walk over a live invocation never re-runs a callback.- Return type:
- click_extra.param_tools.iter_subcommands(command, ctx, *, skip_hidden=True, listing=False)[source]¶
Yield a group’s direct subcommands as
(name, command)pairs.Subcommands are discovered dynamically through
click.Group.list_commands()/get_command(), in listing order, so lazily-registered commands are included. A non-group yields nothing, a name resolving toNoneis skipped, and hidden subcommands are skipped unlessskip_hiddenisFalse(completion specs keep them, flagged hidden; documentation drops them).
- click_extra.param_tools.iter_subcommand_contexts(command, ctx, *, skip_hidden=True)[source]¶
Yield a group’s direct subcommands, each with an introspection context.
Pairs
iter_subcommands()withmake_resilient_context(): every renderer walking a command tree (the man pages, the Markdown and JSON documents, the Carapace spec, the--treeview) descends through here, so a lazy subcommand, the orderclick.Group.list_commands()sets and a name resolving toNoneare handled the same way in all of them.Each context is built under
ctxand named after the subcommand’s registration name, so itscommand_pathand its environment variable prefix are the ones a run reaches.
- click_extra.param_tools.split_option_groups(command)[source]¶
A command’s explicit option groups, split around its ungrouped section.
Hands back the groups drawn before the ungrouped options, then those drawn after. A Click Extra command decides that split itself, through
click_extra.commands.Command.split_option_groups(), so its own sections land past the ungrouped ones. A plain Cloup command has no such method and keeps every group ahead of the ungrouped section, which is Cloup’s own rule.Every renderer reading a command’s sections goes through this, so the split is resolved in one place whatever the command class.
- Parameters:
command (
OptionGroupMixin) – the command whose groups are read.- Return type:
tuple[tuple[OptionGroup,...],tuple[OptionGroup,...]]- Returns:
the groups drawn before the ungrouped section, then those after it.
- click_extra.param_tools.iter_params_for_display(command, ctx)[source]¶
Yield a command’s parameters in the order its help screen lists them.
A Click Extra command keeps two orders apart:
command.paramsis the processing order, which decides when each callback fires, while the help screen reads the presentation order Cloup caches inarguments,option_groupsandungrouped_options, sectioned byclick_extra.commands.Command.split_option_groups()and sorted within a section byparam_priority(). Readingget_params()therefore renders a man page, a Markdown document or a completion spec whose flags no longer match the--helpits reader just saw. This is the accessor every such renderer should go through.Falls back to
get_params()for a command that carries no Cloup option groups, where the two orders are the same list. Any parameter attached after construction, and so absent from the cached groups, is yielded last rather than dropped.
- click_extra.param_tools.walk_command_params(cmd, ctx, parent_keys=(), *, descend=None)[source]¶
Walk the parameter tree of a Click command and all its subcommands.
Yields
(path_keys, param, owning_ctx)for every parameter found oncmdand, recursively, on each subcommand. Each subcommand is walked under its own freshly-built child context (seechild_context()), so context-sensitive metadata (notably the auto-generated environment variable, which derives fromContext.auto_envvar_prefix) is computed at the correct nesting level, with the subcommand’s own context settings applied, rather than inherited from the root.A subcommand whose name collides with a sibling parameter at the same level is skipped: a single fully-qualified path cannot address both an option and a subcommand at once.
- click_extra.param_tools.replay_raw_args(subject_ctx)[source]¶
Re-parse the captured raw arguments to recover per-parameter values.
Click discards the pre-parsed arguments once processing is done, so the value and provenance of each parameter cannot be read back directly. When
RAW_ARGSwas captured on the context (byCommand/Group), replaying it through a fresh parser rebuilds theoptsmapping thatParameter.consume_valueconsults, without re-firing eager callbacks:handle_parse_resultis never called here, only the parser.Returns an empty mapping when no raw arguments were captured, so callers can fall back to parameter defaults.