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, letting search_params(), last_param() and require_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 into nodes.literal.

click_extra.param_tools.iter_inline_literals(text)[source]

Walk text and yield (segment, is_literal) pairs.

Split on INLINE_LITERAL_RE so the consumer can apply different rendering to the literal segments (bold for roff, a literal node for docutils) without re-parsing the regex.

Return type:

Iterator[tuple[str, bool]]

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 / .fi pair: only the control character has to go, or it lands in the output as a stray byte.

Return type:

str

click_extra.param_tools.choice_values(param_type)[source]

The values a click.Choice-like type accepts, spelled as Click completes them.

An Enum member is named by its name, as click.Choice.normalize_choice() does before it folds case, and anything else by str(). A type carrying no choices attribute, 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.

Return type:

tuple[str, ...]

click_extra.param_tools.search_params(params, klass, include_subclasses=True)[source]

Return the one parameter of class klass in params, or None.

The result is typed as klass itself, so a caller needs no isinstance check to use what it found.

Parameters:
  • params (Iterable[Parameter]) – list of parameter instances to search in.

  • klass (type[P]) – the class of the parameter to look for.

  • include_subclasses (bool) – if True (the default), a parameter subclassing klass matches too. If False, only a parameter of exactly klass does.

Raises:

RuntimeError – if more than one parameter matches.

Return type:

P | None

click_extra.param_tools.last_param(params, klass)[source]

Return the last parameter of exactly klass in params, or None.

Unlike search_params(), this matches the exact klass (no subclasses) and tolerates duplicates: when an option is declared more than once (like an explicit @verbosity_option stacked 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.

Parameters:
  • params (Iterable[Parameter]) – the command’s parameter list to scan.

  • klass (type[P]) – the exact parameter class to look for.

Return type:

P | None

click_extra.param_tools.require_sibling_param(params, requester, klass)[source]

Return the sibling klass parameter declared on the same command, or raise.

Some options are inert on their own: they drive machinery owned by a sibling option. --no-config and --validate-config, for instance, both depend on the --config option (ConfigOption). This helper centralizes the lookup so every such option raises the same RuntimeError when its required sibling is missing, naming the offending flag.

Parameters:
  • params (Iterable[Parameter]) – the command’s parameter list to scan.

  • requester (Parameter) – the parameter requiring the sibling, used to build the error message from its flag names and class.

  • klass (type[P]) – the sibling parameter class to look for.

Return type:

P

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_help wins, otherwise the first paragraph of command.help is joined into one line. A truthy deprecated flag appends Click’s own label, so a listing reads the same marker Click’s get_short_help_str() produces, reason string included.

Return type:

str

click_extra.param_tools.resolve_param_help(param, ctx)[source]

Return a parameter’s help text, including the dynamically-generated ones.

Reading param.help covers the options that carry a static string, and misses the ones that compute their help from the context: Click Extra’s own -v / -q derive theirs from the resolved base verbosity, and leave the attribute at None (see VerboseOption.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.

Return type:

str | None

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-Bar answers foo_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-Bar and --FOO-BAR answer the same name, as do --foo--bar and --foo__bar, and --K (the Kelvin sign, U+212A) lands on the same k as --k. Case folding reaches every script and is not length-preserving: --ẞ answers ß, whose upper case is the two letters SS, and a composed café 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 parameter Foo_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 Option should keep the case of an identifier declaration, as it does today, or fold it the way Argument already does. Should Click fold both, no parameter can be named Foo_Bar any more: drop the caution above, and with it the ambiguity branch of _merge_into_template in click_extra.config.schema, which exists only to tell two such names apart.

Return type:

str

click_extra.param_tools.param_spellings(param)[source]

All literal spellings of a parameter: primary opts then secondary_opts.

A boolean flag pair yields both forms (--foo, --no-foo); a plain option yields just its declared names.

Return type:

tuple[str, ...]

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.

Return type:

tuple[str, str]

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 custom flag_value (--no-config), or a counter (-v).

  • "optional": the value may be omitted. Click models this as is_flag=False with a flag_value set, so a bare --color stands for the flag value while --color=never passes an explicit one.

  • "required": consumes a value (--config LOCATION).

Note

The discriminator is Click’s is_flag (plus count), not is_bool_flag: a flag carrying a custom flag_value such as NoConfigOption reports is_bool_flag=False yet 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.

None for a plain option, a counter or an argument, True for a boolean flag, and the declared value otherwise (--color standing for always).

Read from Click’s Option.flag_activation_value, not from flag_value: Click keeps the UNSET sentinel there when no value was declared, and the sentinel stored anywhere it is read back as a value turns the flag off.

Return type:

Any

click_extra.param_tools.is_repeatable(param)[source]

Whether the parameter may be supplied several times (multiple or count).

Return type:

bool

class click_extra.param_tools.ParamStructure[source]

Bases: object

Utilities 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: ShowParamsOption freezes an empty set, while ConfigOption resolves 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. Ask is_excluded() about a parameter of another subcommand.

included_params: frozenset[str] | None

Allowlist of parameter IDs, mutually exclusive with excluded_params.

None disables the allowlist. Otherwise build_param_trees() walks only the subcommands an allowed ID lies under, and resolves the parameters it reaches into excluded_params.

static init_tree_dict(*path, leaf=None)[source]

Nest one dict per key of path, the deepest one holding leaf.

An empty path returns leaf itself.

Return type:

Any

static get_tree_value(tree_dict, *path)[source]

Get in the tree_dict the value located at the path.

Raises KeyError if no item is found at the provided path.

Return type:

Any

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 descend skips 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.

Parameters:

descend (Callable[[tuple[str, ...]], bool] | None) – passed on to walk_command_params(), to skip the subcommands it declines.

Return type:

Iterator[tuple[tuple[str, ...], Parameter]]

Returns:

(keys, param) pairs: the keys leading to the parameter, then the parameter itself.

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 str for unrecognised custom types, since command-line parameters are strings by default.

See the list of custom types provided by Click.

Return type:

type[str | int | float | bool | list]

static get_param_type(param)[source]

Get the Python type of a Click parameter.

Returns str for unrecognised custom types, since command-line parameters are strings by default.

A boolean flag is a bool even 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.

Return type:

type[str | int | float | bool | list]

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_params does not name it. So the answer holds for a parameter of a subcommand that the walk of build_param_trees() skipped. Without an allowlist, the parameter is excluded when excluded_params lists it.

Parameters:

param_id (str) – the fully-qualified ID of the parameter, its path keys joined with PARAM_PATH_SEP.

Return type:

bool

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_params blocklist.

With an allowlist, the tree holds only the parameters included_params names. The walk then skips each subcommand that no allowed ID lies under, so it does not import a lazy subcommand of a LazyGroup that the allowlist leaves out. An empty allowlist walks the root command alone. The parameters the walk reaches and the allowlist leaves out become excluded_params.

Return type:

dict[str, Any]

property params_template: dict[str, Any][source]

Returns a tree-like dictionary whose keys shadows the CLI options and subcommands and values are None.

Perfect to serve as a template for configuration files.

property params_objects: dict[str, Any][source]

Returns a tree-like dictionary whose keys shadows the CLI options and subcommands and values are parameter objects.

Perfect to parse configuration files and user-provided parameters.

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() ignores hidden. An argument has no spec, so it gets None.

Return type:

str | None

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=True so required-argument errors, prompts and eager-option side effects stay dormant: the canonical way to materialize a click.Context purely to read a command’s structure (its parameters, env-var prefix and subcommands), shared by the man-page and Carapace exporters.

Parameters:
  • command (Command) – the command to build the context of.

  • info_name (str | None) – the name the command goes by in that context. Defaults to the command’s own name.

  • parent (Context | None) – the context of the command’s parent, if any.

Return type:

Context

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 own context_class and context_settings, so the context reads like the one a real invocation gets: a subcommand setting its own auto_envvar_prefix names its environment variables after it, where a bare click.Context would derive them from the parent’s prefix. Unlike make_resilient_context(), no parameter is processed, so a walk over a live invocation never re-runs a callback.

Return type:

Context

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 to None is skipped, and hidden subcommands are skipped unless skip_hidden is False (completion specs keep them, flagged hidden; documentation drops them).

Parameters:

listing (bool) – resolve each name to the command the group’s help screen describes, through its listed_command method when it has one. A LazyGroup answers there with a stand-in for a lazy subcommand declaring its help, so the walk imports nothing.

Return type:

Iterator[tuple[str, Command]]

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() with make_resilient_context(): every renderer walking a command tree (the man pages, the Markdown and JSON documents, the Carapace spec, the --tree view) descends through here, so a lazy subcommand, the order click.Group.list_commands() sets and a name resolving to None are handled the same way in all of them.

Each context is built under ctx and named after the subcommand’s registration name, so its command_path and its environment variable prefix are the ones a run reaches.

Parameters:

skip_hidden (bool) – passed on to iter_subcommands().

Return type:

Iterator[tuple[str, Command, Context]]

Returns:

(name, subcommand, subcontext) triples, in listing order.

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.params is the processing order, which decides when each callback fires, while the help screen reads the presentation order Cloup caches in arguments, option_groups and ungrouped_options, sectioned by click_extra.commands.Command.split_option_groups() and sorted within a section by param_priority(). Reading get_params() therefore renders a man page, a Markdown document or a completion spec whose flags no longer match the --help its 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.

Return type:

Iterator[Parameter]

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 on cmd and, recursively, on each subcommand. Each subcommand is walked under its own freshly-built child context (see child_context()), so context-sensitive metadata (notably the auto-generated environment variable, which derives from Context.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.

Parameters:

descend (Callable[[tuple[str, ...]], bool] | None) – called with the path keys of each subcommand, before the group resolves it. The walk skips a subcommand for which it returns False, so a lazy subcommand it declines is not imported. None walks every subcommand.

Return type:

Iterator[tuple[tuple[str, ...], Parameter, Context]]

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_ARGS was captured on the context (by Command/Group), replaying it through a fresh parser rebuilds the opts mapping that Parameter.consume_value consults, without re-firing eager callbacks: handle_parse_result is never called here, only the parser.

Returns an empty mapping when no raw arguments were captured, so callers can fall back to parameter defaults.

Return type:

dict[str, Any]