click_extra package

Expose package-wide elements.

exception click_extra.Abort[source]

Bases: RuntimeError

An internal signalling exception that signals Click to abort.

class click_extra.AccessibleOption(param_decls=None, is_flag=True, default=False, is_eager=True, expose_value=False, help='Accessibility mode: disable colors and render tables in a plain, screen-reader-friendly format.', **kwargs)[source]

Bases: ExtraOption

A pre-configured --accessible switch.

Turning it on (either via the flag or the ACCESSIBLE environment variable) is equivalent to passing --no-color --no-progress --table-format plain, and additionally streams echo_via_pager() output without a pager and turns clear() into a no-op: it strips ANSI codes, silences progress spinners and bars, renders tables without box-drawing characters, and avoids interactive screen takeovers.

Note

It is a one-way flag with no --no-accessible counterpart: to opt back out, pass the explicit --color / --table-format you want, which take precedence anyway (see below). A negation flag would also be the widest option label in the help screen, pushing every other option’s description column to the right.

The switch only adjusts the defaults of the --color and --table-format options, through the context’s default_map. An explicit --color / --table-format on the command line (or in a configuration file) therefore keeps precedence over --accessible.

This option is eager so it lands its defaults before --color and --table-format are resolved.

Note

The values are injected with dict.setdefault(), so they never clobber a colorization or table format already requested by the user. Combined with the ChainMap that ConfigOption layers on top of default_map, this yields the precedence: command line > configuration file > --accessible > built-in defaults.

set_accessible(ctx, param, value)[source]

Publish the accessibility intent and lower color/progress/table defaults.

Reconciles --accessible with the ACCESSIBLE environment variable, stores the result at ACCESSIBLE for output helpers (clear(), echo_via_pager()) to read, then lowers the --color / --progress / --table-format defaults when active. A CLI that never sees --accessible (nor ACCESSIBLE) keeps every default untouched.

Note

The global ACCESSIBLE environment variable is read here rather than wired through the option’s envvar. Click would otherwise list it alongside the auto-generated <CLI>_ACCESSIBLE variable in the --show-params table, making the combined string the widest cell of the env-var column and pushing every other row’s padding out. This mirrors how ColorOption reads NO_COLOR and friends.

Return type:

None

class click_extra.Argument(*args, help=None, **attrs)[source]

Bases: _ParameterMixin, Argument

Wrap cloup.Argument, itself inheriting from click.Argument.

Inherits first from _ParameterMixin to allow future overrides of Click’s Parameter methods.

exception click_extra.BadArgumentUsage(message, ctx=None)[source]

Bases: UsageError

Raised if an argument is generally supplied but the use of the argument was incorrect. This is for instance raised if the number of values for an argument is not correct.

Added in version 6.0.

exception click_extra.BadOptionUsage(option_name, message, ctx=None)[source]

Bases: UsageError

Raised if an option is generally supplied but the use of the option was incorrect. This is for instance raised if the number of arguments for an option is not correct.

Added in version 4.0.

Parameters:

option_name (str) – the name of the option being used incorrectly.

exception click_extra.BadParameter(message, ctx=None, param=None, param_hint=None)[source]

Bases: UsageError

An exception that formats out a standardized error message for a bad parameter. This is useful when thrown from a callback or type as Click will attach contextual information to it (for instance, which parameter it is).

Added in version 2.0.

Parameters:
  • param (Parameter | None) – the parameter object that caused this error. This can be left out, and Click will attach this info itself if possible.

  • param_hint (cabc.Sequence[str] | str | None) – a string that shows up as parameter name. This can be used as alternative to param in cases where custom validation should happen. If it is a string it’s used as such, if it’s a list then each item is quoted and separated.

format_message()[source]
Return type:

str

class click_extra.CLITestCase(cli_parameters=<factory>, skip_platforms=<factory>, only_platforms=<factory>, timeout=None, exit_code=None, strip_ansi=False, output_contains=<factory>, stdout_contains=<factory>, stderr_contains=<factory>, output_regex_matches=<factory>, stdout_regex_matches=<factory>, stderr_regex_matches=<factory>, output_regex_fullmatch=None, stdout_regex_fullmatch=None, stderr_regex_fullmatch=None, execution_trace=None)[source]

Bases: object

A single CLI test case: how to invoke the command and what to expect.

Each case runs the command-under-test once with cli_parameters appended, then checks the captured result against the expectation directives below. A case with no expectation only asserts the command ran (plus exit_code, if set).

cli_parameters: tuple[str, ...] | str

Arguments and options appended to the command-under-test.

A plain string is split into arguments (on spaces on Windows, with shlex elsewhere); a list or tuple is used as-is.

skip_platforms: Trait | Group | str | None | Iterable[Trait | Group | str | None | Iterable[_TNestedReferences]]

Platforms (or platform-group IDs) on which to skip this case.

Accepts extra_platforms identifiers such as linux, macos, windows, in any case, mixed freely with group IDs.

only_platforms: Trait | Group | str | None | Iterable[Trait | Group | str | None | Iterable[_TNestedReferences]]

Restrict this case to these platforms; skip it everywhere else.

The mirror image of skip_platforms, using the same identifiers.

timeout: float | str | None = None

Seconds before the command is killed and the case fails as a timeout.

Falls back to the command’s –timeout default, then to no limit.

exit_code: int | str | None = None

Expected process exit code; the case fails on any other code.

strip_ansi: bool = False

Strip ANSI escape sequences from the captured output before matching.

output_contains: tuple[str, ...] | str

Substrings that must all be present in the combined output.

The combined output interleaves stdout and stderr in the order the command wrote them, matching what a user sees in a terminal. The output_* directives are mutually exclusive with the stdout_* / stderr_* ones: a single subprocess run captures either the merged stream or the separate ones, not both.

stdout_contains: tuple[str, ...] | str

Substrings that must all be present in stdout.

stderr_contains: tuple[str, ...] | str

Substrings that must all be present in stderr.

output_regex_matches: tuple[Pattern | str, ...] | str

Regexes that must each match somewhere in the combined output (searched, re.DOTALL). See output_contains for the merged-stream semantics.

stdout_regex_matches: tuple[Pattern | str, ...] | str

Regexes that must each match somewhere in stdout (searched, re.DOTALL).

stderr_regex_matches: tuple[Pattern | str, ...] | str

Regexes that must each match somewhere in stderr (searched, re.DOTALL).

output_regex_fullmatch: Pattern | str | None = None

Regex that must fully match the combined output, line by line. See output_contains for the merged-stream semantics.

stdout_regex_fullmatch: Pattern | str | None = None

Regex that must fully match stdout, line by line.

stderr_regex_fullmatch: Pattern | str | None = None

Regex that must fully match stderr, line by line.

execution_trace: str | None = None

Rendering of the command execution and its output.

Populated after the case runs, for inspection on failure; not a directive you set in a test plan.

property has_merged_output_directives: bool

Whether any output_* directive (merged stream) is set.

property has_separate_stream_directives: bool

Whether any stdout_* or stderr_* directive (separate streams) is set.

run_cli_test(command, additional_skip_platforms, default_timeout)[source]

Run a CLI command and check its output against the test case.

The provided command can be either:

  • a path to a binary or script to execute;

  • a command name to be searched in the PATH,

  • a command line with arguments to be parsed and executed by the shell.

`{todo} Add support for environment variables. `

Return type:

None

class click_extra.Choice(choices, case_sensitive=True)[source]

Bases: ParamType[ParamTypeValue], Generic[ParamTypeValue]

The choice type allows a value to be checked against a fixed set of supported values.

You may pass any iterable value which will be converted to a tuple and thus will only be iterated once.

The resulting value will always be one of the originally passed choices. See normalize_choice() for more info on the mapping of strings to choices. See Choice for an example.

Parameters:

case_sensitive (bool) – Set to false to make choices case insensitive. Defaults to true.

Changed in version 8.4.0: Now generic in the choice value type. Parameterize with the type of the choice values (Choice[HashType] for an enum, Choice[str] for plain strings) to enable type-checked consumers.

Changed in version 8.2.0: Non-str choices are now supported. It can additionally be any iterable. Before you were not recommended to pass anything but a list or tuple.

Added in version 8.2.0: Choice normalization can be overridden via normalize_choice().

name: str = 'choice'

the descriptive name of this type

to_info_dict()[source]

Gather information that could be useful for a tool generating user-facing documentation.

Use click.Context.to_info_dict() to traverse the entire CLI structure.

Added in version 8.0.

Return type:

ChoiceInfoDict

normalize_choice(choice, ctx)[source]

Normalize a choice value, used to map a passed string to a choice. Each choice must have a unique normalized value.

By default uses Context.token_normalize_func() and if not case sensitive, convert it to a casefolded value.

Added in version 8.2.0.

Return type:

str

get_metavar(param, ctx)[source]

Returns the metavar default for this param if it provides one.

Return type:

str | None

get_missing_message(param, ctx)[source]

Message shown when no choice is passed.

Changed in version 8.2.0: Added ctx argument.

Return type:

str

convert(value, param, ctx)[source]

For a given value from the parser, normalize it and find its matching normalized value in the list of choices. Then return the matched “original” choice.

Return type:

ParamTypeValue

get_invalid_choice_message(value, ctx)[source]

Get the error message when the given choice is invalid.

Parameters:

value (t.Any) – The invalid value.

Added in version 8.2.

Return type:

str

shell_complete(ctx, param, incomplete)[source]

Complete choices that start with the incomplete value.

Parameters:
  • ctx (Context) – Invocation context for this command.

  • param (Parameter) – The parameter that is requesting completion.

  • incomplete (str) – Value being completed. May be empty.

Added in version 8.0.

Return type:

list[CompletionItem]

class click_extra.ChoiceSource(*values)[source]

Bases: Enum

Source of choices for EnumChoice.

KEY = 'key'
NAME = 'name'
VALUE = 'value'
STR = 'str'
class click_extra.CliRunner(charset='utf-8', env=None, echo_stdin=False, catch_exceptions=True, capture='sys')[source]

Bases: CliRunner

Augment click.testing.CliRunner with extra features and bug fixes.

force_color: bool = False

Global class attribute to override the color parameter in invoke.

invoke(cli, *args, input=None, env=None, catch_exceptions=True, color=None, **extra)[source]

Same as click.testing.CliRunner.invoke() with extra features.

  • The first positional parameter is the CLI to invoke. The remaining positional parameters of the function are the CLI arguments. All other parameters are required to be named.

  • The CLI arguments can be nested iterables of arbitrary depth. This is useful for argument composition of test cases with @pytest.mark.parametrize.

  • Allow forcing of the color property at the class-level via force_color attribute.

  • Adds a special case in the form of color="forced" parameter, which allows colored output to be kept, while forcing the initialization of Context.color = True. This is not allowed in current implementation of click.testing.CliRunner.invoke() because of colliding parameters.

  • Strips all ANSI codes from results if color was explicirely set to False.

  • Always prints a simulation of the CLI execution as the user would see it in its terminal. Including colors.

  • Pretty-prints a formatted exception traceback if the command fails.

Parameters:
  • cli (Command) – CLI to invoke.

  • args (str | Path | None | Iterable[str | Path | None | Iterable[Iterable[str | Path | None | Iterable[TNestedArgs]]]]) – can be nested iterables composed of str, pathlib.Path objects and None values. The nested structure will be flattened and None values will be filtered out. Then all elements will be casted to str. See args_cleanup() for details.

  • input (str | bytes | IO | None) – same as click.testing.CliRunner.invoke().

  • env (Mapping[str, str | None] | None) – same as click.testing.CliRunner.invoke().

  • catch_exceptions (bool) – same as click.testing.CliRunner.invoke().

  • color (bool | Literal['forced'] | None) – If a boolean, the parameter will be passed as-is to click.testing.CliRunner.isolation(). If "forced", the parameter will be passed as True to click.testing.CliRunner.isolation() and an extra color=True parameter will be passed to the invoked CLI.

  • extra (Any) – same as click.testing.CliRunner.invoke(), but colliding parameters are allowed and properly passed on to the invoked CLI.

Return type:

Result

exception click_extra.ClickException(message)[source]

Bases: Exception

An exception that Click can handle and show to the user.

exit_code = 1

The exit code for this exception.

format_message()[source]
Return type:

str

show(file=None)[source]
Return type:

None

class click_extra.ClickExtraConfig(test_plan=<factory>, prebake=<factory>)[source]

Bases: object

Schema for the [tool.click-extra] configuration section.

Wired as the config_schema of the top-level click-extra group, so every subcommand reads the same section and pulls its own sub-table through get_tool_config().

test_plan: TestPlanConfig

The [tool.click-extra.test-plan] sub-table (file/inline/timeout).

prebake: PrebakeConfig

The [tool.click-extra.prebake] sub-table (target module).

class click_extra.Color[source]

Bases: FrozenSpace

Colors accepted by Style and click.style().

black = 'black'
red = 'red'
green = 'green'
yellow = 'yellow'
blue = 'blue'
magenta = 'magenta'
cyan = 'cyan'
white = 'white'
reset = 'reset'
bright_black = 'bright_black'
bright_red = 'bright_red'
bright_green = 'bright_green'
bright_yellow = 'bright_yellow'
bright_blue = 'bright_blue'
bright_magenta = 'bright_magenta'
bright_cyan = 'bright_cyan'
bright_white = 'bright_white'
class click_extra.ColorOption(param_decls=None, is_flag=False, flag_value='always', default='auto', is_eager=True, expose_value=False, help='Colorize the output. A bare --color is the same as --color=always.', **kwargs)[source]

Bases: ExtraOption

A pre-configured --color[=WHEN] tri-state option.

Mirrors the GNU coreutils convention: WHEN is one of COLOR_WHEN (auto, always or never), and a bare --color (no value) means always. The negative alias --no-color is carried by the separate NoColorOption, because Click forbids attaching /--no-x secondary flags to a value option.

The resolved tri-state lands on ctx.color, the Click-standard attribute that echo() reads through its resolve_color_default()should_strip_ansi() chain: True keeps ANSI codes, False strips them, None (auto) defers to the output stream’s TTY status.

This option is eager by default, so other eager options (like --version) are rendered with the resolved color state.

Note

--color is deliberately not wired to an envvar. The color environment variables (NO_COLOR, FORCE_COLOR, …) are read manually through resolve_color_env(). Letting Click manage them would dump the whole color_envvars set into the --show-params env-var column, and only bind one variable per option anyway.

add_to_parser(parser, ctx)[source]

Register the option, then teach the parser GNU optional-argument rules.

Click’s optional-value parser binds --color to the next token whenever it does not look like an option, so mycli --color subcommand would consume subcommand as the color value and fail. GNU instead binds an optional argument only when it is attached with =.

This wraps the parser’s long-option matcher so a bare --color replays as --color=<flag_value> (always) and leaves the following argument untouched, while --color=<when> keeps working. The wrapper stays inert for every option that does not carry _gnu_optional_value, so it is safe to install on the shared parser.

Return type:

None

set_color(ctx, param, value)[source]

Resolve --color=<WHEN> against the environment and pin ctx.color.

Precedence, highest first:

  1. An explicit --color on the command line.

  2. The color environment variables, but only when the value comes from the built-in default. A configuration file or --accessible (both seen here as a non-DEFAULT source) therefore wins over the environment, matching AccessibleOption.

  3. A color state already pinned by --no-color, a forced test runner, or an explicit Context(color=...): preserved when this option only resolves to auto from its default.

  4. The auto default, leaving ctx.color at None for TTY detection.

Return type:

None

class click_extra.ColumnSpec(id, label, description='')[source]

Bases: object

Rich description of a single column in a rendered table.

Three fields, all required-by-convention even though description defaults to empty so quick prototypes do not have to write a sentence for every column:

  • id: stable, snake_case identifier used by --columns to address the column, to key structured-format serializations, and to thread state through click_extra.context.COLUMNS.

  • label: the human-readable header shown at the top of the rendered table.

  • description: a MyST/Markdown blurb describing what the column represents. Used to auto-generate the column reference in the documentation.

Note

Frozen + slots: instances are immutable and lightweight. Tuples of ColumnSpec are intended to be defined as module-level constants (like click_extra.parameters.ShowParamsOption.TABLE_HEADERS).

id: str

Stable, snake_case identifier addressing this column from CLI flags and code.

label: str

Human-readable header label rendered at the top of the table.

description: str

MyST/Markdown description of what the column carries.

Used to auto-generate the Available columns section in the docs via the show_params_columns_table MyST substitution. Plain text without inline markup is fine: links and emphasis are optional sugar.

class click_extra.ColumnsOption(param_decls=None, columns=None, type=None, default=(), expose_value=False, is_eager=True, help='Restrict and reorder table columns, SQL SELECT-style. Comma-separated list of column IDs. Default: all columns in canonical order.', **kwargs)[source]

Bases: ExtraOption

A --columns option that lets users restrict and reorder table columns.

Accepts a comma-separated list of column IDs, SQL-SELECT-style:

$ my-cli --columns id,spec,value --show-params

The selection is stored in ctx.meta[click_extra.context.COLUMNS] and consumed by table-rendering callbacks (like click_extra.parameters.ShowParamsOption) to project rows + headers before rendering.

Pass columns= at construction time with the column registry the option should advertise: the help text then lists the accepted IDs and the default selection, and the callback validates the user input against that registry so unknown IDs fail fast with a click.UsageError. Without columns=, the option stays generic: it parses any IDs and leaves validation to the downstream consumer.

Empty / unset means render every column in canonical order: the default behavior, indistinguishable from not passing --columns at all.

columns: tuple[ColumnSpec, ...]

Column registry this option advertises and validates against (may be empty).

init_columns(ctx, param, columns)[source]

Store the selected column IDs on the context for later projection.

Validation of the IDs against the registry happens inside convert(), before this callback runs, so this just threads the parsed selection onto the context.

Return type:

None

class click_extra.Command(*args, version_fields=None, config_schema=None, schema_strict=False, fallback_sections=(), config_validators=(), included_params=None, extra_option_at_end=True, populate_auto_envvars=True, extra_keywords=None, excluded_keywords=None, **kwargs)[source]

Bases: _HelpColorsMixin, Command

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

List of extra parameters:

Parameters:
  • 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.

  • 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.

  • 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.

  • populate_auto_envvars (bool) – forces all parameters to have their auto-generated environment variables registered. This address the shortcoming of click which only evaluates them dynamically. By forcing their registration, the auto-generated environment variables gets displayed in the help screen, fixing click#2483 issue. On Windows, environment variable names are case-insensitive, so we normalize them 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 --show-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

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.

Return type:

Any

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

Intercept the call to the original click.core.Command.make_context so we can keep a copy of the raw, pre-parsed arguments provided to the CLI.

The result are passed to our own Context constructor which is able to initialize the context’s meta property under our own click_extra.context.RAW_ARGS entry. This will be used in ShowParamsOption.print_params() to print the table of parameters fed to the CLI.

See also

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

Return type:

Any

parse_args(ctx, args)[source]

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

Also settles the color options before delegating, so --color / --no-color colorize the eager help and version screens regardless of their position on the command line. See _resolve_color_eagerly.

Return type:

list[str]

class click_extra.CommandCollection(name=None, sources=None, **kwargs)[source]

Bases: Group

A Group that looks up subcommands on other groups. If a command is not found on this group, each registered source is checked in order. Parameters on a source are not added to this group, and a source’s callback is not invoked when invoking its commands. In other words, this “flattens” commands in many groups into this one group.

Parameters:
  • name (str | None) – The name of the group command.

  • sources (list[Group] | None) – A list of Group objects to look up commands from.

  • kwargs (Any) – Other arguments passed to Group.

Changed in version 8.2: This is a subclass of Group. Commands are looked up first on this group, then each of its sources.

sources: list[Group]

The list of registered groups.

add_source(group)[source]

Add a group as a source of commands.

Return type:

None

get_command(ctx, cmd_name)[source]

Given a context and a command name, this returns a Command object if it exists or returns None.

Return type:

Command | None

list_commands(ctx)[source]

Returns a list of subcommand names in the order they should appear.

Return type:

list[str]

class click_extra.ConfigFormat(*values)[source]

Bases: Enum

All configuration formats, associated to their support status.

The first element of the tuple is a sequence of file extensions associated to the format. Patterns are fed to wcmatch.glob for matching, and are influenced by the flags set on the ConfigOption instance.

The second element indicates whether the format is supported or not, depending on the availability of the required third-party packages. This evaluation is performed at runtime when this module is imported.

Caution

The order is important for both format members and file patterns. It defines the priority order in which formats are tried when multiple candidate files are found.

Todo

Add support for JWCC / hujson format?

TOML = (('*.toml',), True, 'TOML')
YAML = (('*.yaml', '*.yml'), True, 'YAML')
JSON = (('*.json',), True, 'JSON')
JSON5 = (('*.json5',), True, 'JSON5')
JSONC = (('*.jsonc',), True, 'JSONC')
HJSON = (('*.hjson',), True, 'Hjson')
INI = (('*.ini',), True, 'INI')
XML = (('*.xml',), True, 'XML')
PYPROJECT_TOML = (('pyproject.toml',), True, 'pyproject.toml')
property label: str

Human-friendly name of the format for display in messages.

property enabled: bool

Returns True if the format is supported, False otherwise.

property patterns: tuple[str, ...]

Returns the default file patterns associated to the format.

class click_extra.ConfigOption(param_decls=None, metavar='CONFIG_PATH', type=UNPROCESSED, help='Location of the configuration file. Supports local path with glob patterns or remote URL.', is_eager=True, expose_value=False, file_format_patterns=None, file_pattern_flags=4104, roaming=True, force_posix=False, search_pattern_flags=285504, search_parents=False, stop_at=Sentinel.VCS, excluded_params=None, included_params=None, strict=False, config_schema=None, schema_strict=False, fallback_sections=(), config_validators=(), **kwargs)[source]

Bases: ExtraOption, ParamStructure

A pre-configured option adding --config CONFIG_PATH.

Takes as input a path to a file or folder, a glob pattern, or an URL.

  • is_eager is active by default so the callback gets the opportunity to set the default_map of the CLI before any other parameter is processed.

  • default is set to the value returned by self.default_pattern(), which is a pattern combining the default configuration folder for the CLI (as returned by click.get_app_dir()) and all supported file formats.

    Attention

    Default search pattern must follow the syntax of wcmatch.glob.

  • excluded_params are parameters which, if present in the configuration file, will be ignored and not applied to the CLI. Items are expected to be the fully-qualified ID of the parameter, as produced in the output of --show-params. Will default to the value of DEFAULT_EXCLUDED_PARAMS.

  • included_params is the inverse of excluded_params: only the listed parameters will be loaded from the configuration file. Cannot be used together with excluded_params.

file_format_patterns: dict[ConfigFormat, tuple[str, ...]]

Mapping of ConfigFormat to their associated file patterns.

Can be a string or a sequence of strings. This defines which configuration file formats are supported, and which file patterns are used to search for them.

Note

All formats depending on third-party dependencies that are not installed will be ignored.

Attention

File patterns must follow the syntax of wcmatch.fnmatch.

file_pattern_flags

Flags provided to all calls of wcmatch.fnmatch.

Applies to the matching of file names against supported format patterns specified in file_format_patterns.

Important

The SPLIT flag is always forced, as our multi-pattern design relies on it.

force_posix

Configuration for default folder search.

roaming and force_posix are fed to click.get_app_dir() to determine the location of the default configuration folder.

search_pattern_flags

Flags provided to all calls of wcmatch.glob.

Applies to both the default pattern and any user-provided pattern.

Important

The BRACE flag is always forced, so that multi-format default patterns using {pat1,pat2,...} syntax expand correctly.

The NODIR flag is always forced, to optimize the search for files only.

search_parents

Indicates whether to walk back the tree of parent folders when searching for configuration files.

stop_at

Boundary for parent directory walking.

  • None: walk up to filesystem root.

  • VCS: stop at the nearest VCS root (.git or .hg) (default).

  • A Path or str: stop at that directory.

included_params: frozenset[str] | None

Allowlist of parameter IDs, mutually exclusive with excluded_params.

None disables the allowlist. It is resolved into excluded_params by build_param_trees(), once every parameter ID is known.

strict

Defines the strictness of the configuration loading.

  • If True, raise an error if the configuration file contain parameters not recognized by the CLI.

  • If False, silently ignore unrecognized parameters.

config_schema

Optional schema for structured access to configuration values.

When set, the app’s configuration section is extracted from the parsed config file, normalized (hyphens replaced with underscores), flattened (nested dicts joined with _), and passed to this callable to produce a typed configuration object.

Supports:

  • Dataclass types: detected via __dataclass_fields__. Keys are normalized, nested dicts are flattened, and the result is filtered to known fields before instantiation. This allows nested config sections (like [tool.myapp.sub-section]) to map directly to flat dataclass fields (like sub_section_key).

  • Any callable dict T: called directly with the raw dict. Works with Pydantic’s Model.model_validate, attrs, or custom factory functions. The caller is responsible for key normalization and flattening.

The resulting object is stored in ctx.meta[click_extra.context.TOOL_CONFIG] and can be retrieved via get_tool_config.

schema_strict

Strictness for schema validation (separate from strict).

  • If True, raise ValueError when the config section contains keys that do not match any dataclass field (after normalization and flattening). Only applies when config_schema is a dataclass.

  • If False, silently ignore unrecognized keys.

Note

This is distinct from strict, which controls whether merge_default_map rejects config keys not matching CLI parameters. schema_strict validates against dataclass fields instead.

fallback_sections: Sequence[str]

Legacy section names to try when the app’s own section is empty.

Useful when a CLI tool has been renamed: old configuration files that still use [tool.old-name] (TOML), old-name: (YAML), or {"old-name": …} (JSON) are recognized with a deprecation warning. Works with all configuration formats.

config_validators: tuple[ConfigValidator, ...]

Extension validators for sub-trees of the configuration file.

Each ConfigValidator targets a dotted extension_path relative to the app section. Validators run after click-extra’s built-in CLI-parameter strict check (during --validate-config) and after the schema callable produces the typed configuration object (during normal config loading).

The list is seeded with click-extra’s built-in validators (currently the one for [tool.<cli>.themes.<name>] tables, see click_extra.theme.validate_themes_config()); user-supplied validators are appended after them. App code that registers its own validator on the same extension_path simply runs alongside the built-in: both validators are called, both sets of errors surface.

property excluded_params: frozenset[str][source]

Generates the default list of fully-qualified IDs to exclude.

Danger

It is only called once to produce the default exclusion list if the user did not provided its own.

It was not implemented in the constructor but made as a property, to allow for a just-in-time call within the current context. Without this trick we could not have fetched the CLI name.

property file_pattern: str[source]

Compile all file patterns from the supported formats.

Uses , (comma) notation to combine multiple patterns, suitable for wcmatch brace expansion ({pat1,pat2,...}).

Returns a single pattern string.

default_pattern()[source]

Returns the default pattern used to search for the configuration file.

Defaults to <app_dir>/{*.toml,*.json,*.ini}. Where <app_dir> is produced by the click.get_app_dir() method. The result depends on OS and is influenced by the roaming and force_posix properties.

Multiple file format patterns are wrapped with {…} brace-expansion syntax so that wcmatch.glob correctly applies the directory prefix to every sub-pattern.

Todo

Use platformdirs for more advanced configuration folder detection?

Return type:

str

get_help_extra(ctx)[source]

Replaces the default value of the configuration option.

Display a pretty path that is relative to the user’s home directory:

~/folder/my_cli/{*.toml,*.json,*.ini}

Instead of the full absolute path:

/home/user/folder/my_cli/{*.toml,*.json,*.ini}

Caution

This only applies when the GLOBTILDE flag is set in search_pattern_flags.

Return type:

OptionHelpExtra

parent_patterns(pattern)[source]

Generate (root_dir, file_pattern) pairs for searching.

Each yielded pair can be passed directly to glob.iglob(file_pattern, root_dir=root_dir) so that every sub-pattern (whether from BRACE or SPLIT expansion) is correctly scoped to the same directory.

root_dir is None for entirely magic patterns that will be evaluated relative to the current working directory.

Stops when reaching the root folder, the stop_at boundary, or an inaccessible directory.

Return type:

Iterable[tuple[str | None, str]]

search_and_read_file(pattern)[source]

Search filesystem or URL for files matching the pattern.

If pattern is an URL, download its content. A pattern is considered an URL only if it validates as one and starts with http:// or https://. All other patterns are considered glob patterns for local filesystem search.

Returns an iterator of the normalized location and its raw content, for each one matching the pattern. Only files are returned, directories are silently skipped.

This method returns the raw content of all matching patterns, without trying to parse them. If the content is empty, it is still returned as-is.

Also includes lookups into parents directories if self.search_parents is True.

Raises FileNotFoundError if no file was found after searching all locations.

Return type:

Iterable[tuple[Path | URL, str]]

parse_conf(content, formats)[source]

Parse the content with the given formats.

Tries to parse the given raw content string with each of the given formats, in order. Yields the resulting data structure for each successful parse.

Attention

Formats whose parsing raises an exception or does not return a dict are considered a failure and are skipped.

This follows the parse, don’t validate principle.

Return type:

Iterable[dict[str, Any] | None]

read_and_parse_conf(pattern)[source]

Search for a parseable configuration file.

Returns the location and data structure of the first configuration matching the pattern.

Only return the first match that:

  • exists,

  • is a file,

  • is not empty,

  • match file format patterns,

  • can be parsed successfully, and

  • produce a non-empty data structure.

Raises FileNotFoundError if no configuration file was found matching the criteria above.

Returns (None, None) if files were found but none could be parsed.

Return type:

tuple[Path | URL, dict[str, Any]] | tuple[None, None]

load_ini_config(content)[source]

Utility method to parse INI configuration file.

Internal convention is to use a dot (., as set by PARAM_PATH_SEP) in section IDs as a separator between levels. This is a workaround the limitation of INI format which doesn’t allow for sub-sections.

Returns a ready-to-use data structure.

Return type:

dict[str, Any]

merge_default_map(ctx, user_conf)[source]

Save the user configuration into the context’s default_map.

Merge the user configuration into the pre-computed template structure, which filters out all unrecognized options not supported by the command, then hand the result to _install_default_map().

Opaque sub-trees declared by the schema or by registered ConfigValidator instances are stripped from the conf before the CLI-parameter strict check, so user-controlled keys (like mappings whose keys are data, not flag names) don’t trip strict=True.

Note

This recomputes the filtered config that run_config_validation() already produces as merged_conf. load_conf() installs that result directly and skips this method; it stays as the standalone entry point for external callers.

Return type:

None

load_conf(ctx, param, path_pattern)[source]

Fetch parameter values from a configuration file and set them as defaults.

User configuration is merged to the context’s default_map, like Click does.

By relying on Click’s default_map, we make sure that precedence is respected. Direct CLI parameters, environment variables or interactive prompts take precedence over any values from the config file.

Hint

Once loading is complete, the resolved file path and its full parsed content are stored in ctx.meta[click_extra.context.CONF_SOURCE] and ctx.meta[click_extra.context.CONF_FULL] respectively. This is the recommended way to identify which configuration file was loaded.

We intentionally do not add a custom ParameterSource.CONFIG_FILE enum member: ParameterSource is a closed enum in Click, and monkeypatching it would be fragile. Besides, config values end up in default_map, so Click already reports them as ParameterSource.DEFAULT_MAP, which is accurate.

Return type:

None

class click_extra.ConfigValidator(extension_path, validator, description='')[source]

Bases: object

Register an app-defined extension validator for one sub-tree of the configuration file.

Apps register validators via the config_validators= kwarg on ConfigOption (or the matching decorator) to extend click-extra’s built-in CLI-parameter strict check with custom validation logic. Each validator targets a single dotted extension_path relative to the app’s configuration section. Click-extra passes the matching sub-tree straight through to the registered validator: the strict check skips it, the schema machinery treats it as opaque, and the user’s logic owns the result. The validator runs both during --validate-config and during normal config loading.

Parameters:
  • extension_path (str) – Dotted path of the sub-tree the validator owns, relative to the app’s section in the configuration file. For example, an app named my-cli with extension_path="managers" receives the contents of the [my-cli.managers] table.

  • validator (Callable[[dict[str, Any]], None]) – Callable taking the sub-tree dict and raising ValidationError on failure. Must be a pure function: no side effects on the click context, no print statements. The caller decides how to surface the error.

  • description (str) – Optional human-readable summary of what the validator checks. Surfaces in documentation generators that introspect the decorator (like autodoc), and may be reused in --help text in a future release.

extension_path: str
validator: Callable[[dict[str, Any]], None]
description: str = ''
class click_extra.ConstraintMixin(*args, constraints=(), show_constraints=None, **kwargs)[source]

Bases: object

Provides support for constraints.

Parameters:
  • constraints (Sequence[BoundConstraintSpec | BoundConstraint]) – sequence of constraints bound to specific groups of parameters. Note that constraints applied to option groups are collected from the option groups themselves, so they don’t need to be included in this argument.

  • show_constraints (bool | None) – whether to include a “Constraint” section in the command help. This is also available as a context setting having a lower priority than this attribute.

  • args (Any) – positional arguments forwarded to the next class in the MRO

  • kwargs (Any) – keyword arguments forwarded to the next class in the MRO

optgroup_constraints

Constraints applied to OptionGroup instances.

param_constraints: Tuple[BoundConstraint, ...]

Constraints registered using @constraint (or equivalent method).

all_constraints

All constraints applied to parameter/option groups of this command.

parse_args(ctx, args)[source]
Return type:

List[str]

get_param_by_name(name)[source]
Return type:

Parameter

get_params_by_name(names)[source]
Return type:

Sequence[Parameter]

format_constraints(ctx, formatter)[source]
Return type:

None

must_show_constraints(ctx)[source]
Return type:

bool

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

Bases: Context

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

Also defaults color to True for root contexts (those without a parent), so help screens are always colorized, even when piped. Click’s own default is None (auto-detect via TTY), which strips colors in non-interactive contexts.

Parent-to-child color inheritance is handled by Click itself at Context.__init__ time, so no property override is needed.

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.

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.

formatter_class

alias of HelpFormatter

class click_extra.DateTime(formats=None)[source]

Bases: ParamType[datetime]

The DateTime type converts date strings into datetime objects.

The format strings which are checked are configurable, but default to some common (non-timezone aware) ISO 8601 formats.

When specifying DateTime formats, you should only pass a list or a tuple. Other iterables, like generators, may lead to surprising results.

The format strings are processed using datetime.strptime, and this consequently defines the format strings which are allowed.

Parsing is tried using each format, in order, and the first format which parses successfully is used.

Parameters:

formats (Sequence[str] | None) – A list or tuple of date format strings, in the order in which they should be tried. Defaults to '%Y-%m-%d', '%Y-%m-%dT%H:%M:%S', '%Y-%m-%d %H:%M:%S'.

name: str = 'datetime'

the descriptive name of this type

formats: Sequence[str]
to_info_dict()[source]

Gather information that could be useful for a tool generating user-facing documentation.

Use click.Context.to_info_dict() to traverse the entire CLI structure.

Added in version 8.0.

Return type:

DateTimeInfoDict

get_metavar(param, ctx)[source]

Returns the metavar default for this param if it provides one.

Return type:

str | None

convert(value, param, ctx)[source]

Convert the value to the correct type. This is not called if the value is None (the missing value).

This must accept string values from the command line, as well as values that are already the correct type. It may also convert other compatible types.

The param and ctx arguments may be None in certain situations, such as when converting prompt input.

If the value cannot be converted, call fail() with a descriptive message.

Parameters:
  • value (t.Any) – The value to convert.

  • param (Parameter | None) – The parameter that is using this type to convert its value. May be None.

  • ctx (Context | None) – The current context that arrived at this value. May be None.

Return type:

datetime

class click_extra.EnumChoice(choices, case_sensitive=False, choice_source=ChoiceSource.STR, show_aliases=False)[source]

Bases: Choice

Choice type for Enum.

Allows to select which part of the members to use as choice strings, by setting the choice_source parameter to one of:

  • ChoiceSource.KEY or ChoiceSource.NAME to use the key (the name property),

  • ChoiceSource.VALUE to use the value,

  • ChoiceSource.STR to use the str() string representation, or

  • A custom callable that takes an Enum member and returns a string.

Defaults to ChoiceSource.STR, which only requires you to define the __str__() method on your Enum to produce beautiful choice strings.

Same as click.Choice, but takes an Enum as choices.

Also defaults to case-insensitive matching.

choices: tuple[str, ...]

The strings available as choice.

Hint

Contrary to the parent Choice class, we store choices directly as strings, not the Enum members themselves. That way there is no surprises when displaying them to the user.

This trick bypass Enum-specific code path in the Click library. Because, after all, a terminal environment only deals with strings: arguments, parameters, parsing, help messages, environment variables, etc.

get_choice_string(member)[source]

Derive the choice string from the given Enum’s member.

Return type:

str

normalize_choice(choice, ctx)[source]

Expand the parent’s normalize_choice() to accept Enum members as input.

Parent method expects a string, but here we allow passing Enum members too.

Return type:

str

convert(value, param, ctx)[source]

Convert the input value to the corresponding Enum member.

The parent’s convert() is going to return the choice string, which we then map back to the corresponding Enum member.

Return type:

Enum

class click_extra.ExtraOption(*args, group=None, **attrs)[source]

Bases: Option

Dedicated to option implemented by click-extra itself.

Provides a way to identify Click Extra’s own options with certainty, and restores the pre-Click-8.4.0 contract that eager callbacks can introspect their own parameter source from within their own callback.

Note

This is the one click-extra class that deliberately keeps the Extra prefix. The 8.0.0 cleanup dropped it everywhere else (ExtraCommand became Command, ExtraContext became Context, and so on), shadowing the matching Cloup or Click class. Here the plain Option name is already taken by the user-facing enhanced wrapper this class subclasses, so the prefix is not legacy baggage but a real distinction: ExtraOption marks click-extra’s own built-in options. That marker is load-bearing, since Command sorts parameters with isinstance(param, ExtraOption) to push the built-in options to the end.

Note

Bracket fields (envvar, default, range, required) cannot be pre-styled in get_help_record() because Click’s text wrapper splits lines after the record is returned, which would break ANSI codes that span wrapped boundaries. Styling is instead applied post-wrapping in HelpFormatter._style_bracket_fields(), which uses the structured data from Option.get_help_extra() to identify each field by its label.

Note

Built-in option subclasses share a common shape: their __init__ defaults param_decls to the option’s canonical flags and wires an eager callback via kwargs.setdefault("callback", self.<callback>). Every callback name encodes its role with a verb prefix. The common roles are:

  • set_<key> publishes a resolved value to ctx.meta (set_color, set_no_color, set_theme, set_telemetry, set_progress, set_accessible, set_zero_exit, the verbosity options’ set_level);

  • init_<system> additionally installs a ctx helper or records a snapshot (init_timer, init_formatter, init_columns, init_sort);

  • validate_<thing> coerces and validates the raw input (validate_jobs, validate_config);

  • print_* renders output and exits (print_man, print_params, print_and_exit).

A few options own a richer operation and name it with its own verb rather than forcing one of the above. ConfigOption wires load_conf to read, parse, and merge a configuration file, and NoConfigOption wires check_sibling_config_option to assert that a sibling --config option exists.

handle_parse_result(ctx, opts, args)[source]

Record the parameter source before delegating to the base implementation.

Warning

Click 8.4.0 (PR pallets/click#3404) reordered Parameter.handle_parse_result so ctx.set_parameter_source runs after process_value. Eager callbacks that introspect their own provenance via ctx.get_parameter_source(self.name) therefore read None instead of the actual source. ColorOption, ConfigOption, and ShowParamsOption all rely on this introspection to decide whether an env var should override the default (--color), whether the --config path was user-supplied, and what to render in the Source column of --show-params.

Click 8.4.1 restored the pre-8.4.0 contract upstream (PR pallets/click#3484), so this override only matters for Click 8.4.0 itself, which sits inside click-extra’s supported >= 8.3.1 range. Pre-recording the source here for eager options keeps that contract on every supported Click. super().handle_parse_result re-records the same value at the canonical time, so the slot arbitration logic introduced by #3404 is unaffected: slot_empty is computed from ctx.params, not from _parameter_source.

consume_value runs twice as a side effect: once here and once in super. Both calls are pure for click-extra’s existing eager flag-style options (no env var side effects, no prompt). Should a future eager subclass need prompt behavior, this override would need to cache the result instead.

The pre-record is skipped when the slot already carries a source from an earlier option sharing the same name (Click’s feature-switch pattern), so the arbitration logic in super still sees the original existing_source rather than a stale rewrite from this option.

class click_extra.File(mode='r', encoding=None, errors='strict', lazy=None, atomic=False)[source]

Bases: ParamType[IO[Any]]

Declares a parameter to be a file for reading or writing. The file is automatically closed once the context tears down (after the command finished working).

Files can be opened for reading or writing. The special value - indicates stdin or stdout depending on the mode.

By default, the file is opened for reading text data, but it can also be opened in binary mode or for writing. The encoding parameter can be used to force a specific encoding.

The lazy flag controls if the file should be opened immediately or upon first IO. The default is to be non-lazy for standard input and output streams as well as files opened for reading, lazy otherwise. When opening a file lazily for reading, it is still opened temporarily for validation, but will not be held open until first IO. lazy is mainly useful when opening for writing to avoid creating the file until it is needed.

Files can also be opened atomically in which case all writes go into a separate file in the same folder and upon completion the file will be moved over to the original location. This is useful if a file regularly read by other users is modified.

See File Arguments for more information.

Changed in version 2.0: Added the atomic parameter.

name: str = 'filename'

the descriptive name of this type

envvar_list_splitter: ClassVar[str] = ':'

if a list of this type is expected and the value is pulled from a string environment variable, this is what splits it up. None means any whitespace. For all parameters the general rule is that whitespace splits them up. The exception are paths and files which are split by os.path.pathsep by default (“:” on Unix and “;” on Windows).

to_info_dict()[source]

Gather information that could be useful for a tool generating user-facing documentation.

Use click.Context.to_info_dict() to traverse the entire CLI structure.

Added in version 8.0.

Return type:

FileInfoDict

resolve_lazy_flag(value)[source]
Return type:

bool

convert(value, param, ctx)[source]

Convert the value to the correct type. This is not called if the value is None (the missing value).

This must accept string values from the command line, as well as values that are already the correct type. It may also convert other compatible types.

The param and ctx arguments may be None in certain situations, such as when converting prompt input.

If the value cannot be converted, call fail() with a descriptive message.

Parameters:
  • value (str | os.PathLike[str] | t.IO[t.Any]) – The value to convert.

  • param (Parameter | None) – The parameter that is using this type to convert its value. May be None.

  • ctx (Context | None) – The current context that arrived at this value. May be None.

Return type:

t.IO[t.Any]

shell_complete(ctx, param, incomplete)[source]

Return a special completion marker that tells the completion system to use the shell to provide file path completions.

Parameters:
  • ctx (Context) – Invocation context for this command.

  • param (Parameter) – The parameter that is requesting completion.

  • incomplete (str) – Value being completed. May be empty.

Added in version 8.0.

Return type:

list[CompletionItem]

exception click_extra.FileError(filename, hint=None)[source]

Bases: ClickException

Raised if a file cannot be opened.

ui_filename: str
format_message()[source]
Return type:

str

class click_extra.FloatRange(min=None, max=None, min_open=False, max_open=False, clamp=False)[source]

Bases: _NumberRangeBase[float], FloatParamType

Restrict a click.FLOAT value to a range of accepted values. See Int and Float Ranges.

If min or max are not passed, any value is accepted in that direction. If min_open or max_open are enabled, the corresponding boundary is not included in the range.

If clamp is enabled, a value outside the range is clamped to the boundary instead of failing. This is not supported if either boundary is marked open.

Changed in version 8.0: Added the min_open and max_open parameters.

name: str = 'float range'

the descriptive name of this type

class click_extra.Formatter(fmt=None, datefmt=None, style='%', validate=True, *, defaults=None)[source]

Bases: Formatter

Click Extra’s default log formatter.

Initialize the formatter with specified format strings.

Initialize the formatter either with the specified format string, or a default as described above. Allow for specialized date formatting with the optional datefmt argument. If datefmt is omitted, you get an ISO8601-like (or RFC 3339-like) format.

Use a style parameter of ‘%’, ‘{’ or ‘$’ to specify that you want to use one of %-formatting, str.format() ({}) formatting or string.Template formatting in your format string.

Changed in version 3.2: Added the style parameter.

formatMessage(record)[source]

Colorize the record’s log level name before calling the standard formatter.

Colors are sourced from a click_extra.theme.HelpTheme, resolved per-invocation via click_extra.theme.get_current_theme().

Return type:

str

class click_extra.Group(*args, help_command=True, **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.

command_class

alias of Command

group_class

alias of type

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

Like cloup.Group.add_command, but replaces an auto-injected HelpCommand when the user registers their own help subcommand.

Return type:

None

invoke(ctx)[source]

Inject _default_subcommands and _prepend_subcommands from config.

If the user has not provided any subcommands explicitly, and the loaded configuration contains a _default_subcommands list for this group, those subcommands are injected into ctx.protected_args so that Click’s normal Group.invoke() dispatches them.

_prepend_subcommands always prepends subcommands to the invocation, regardless of whether CLI subcommands were provided. Only works with chain=True groups.

Return type:

Any

class click_extra.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: ColorizedCommand

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.HelpFormatter(*args, **kwargs)[source]

Bases: HelpFormatter

Extends Cloup’s custom HelpFormatter to highlights options, choices, metavars and default values.

This is being discussed for upstream integration at:

Forces theme to the active one for the current Click context.

Also transform Cloup’s standard HelpTheme to our own HelpTheme.

Resolves the active theme via click_extra.theme.get_current_theme(), which reads the per-invocation pick from the Click context (set by ThemeOption) and falls back to the module-level default when no context is active.

theme: HelpTheme
write_usage(prog, args='', prefix=None)[source]

ANSI-aware override of cloup.HelpFormatter.write_usage.

On Click 8.3.x, click.formatting.wrap_text measures line length with raw len(), counting every byte of the ANSI escape sequences embedded in initial_indent (the styled Usage: heading + invoked-command name). With 24-bit RGB themes (like Solarized Dark, Dracula, Nord, Monokai), each styled token carries 17+ extra bytes of escape, which inflates the measured line beyond the width budget and causes premature wraps mid-token: [OPTIONS\n  ].

Cloup styles prefix and prog then delegates to click’s HelpFormatter.write_usage(), inheriting the bug. This override re-applies the same styling, then bypasses wrap_text whenever the visible content fits on a single line: the common case for short usage strings where wrapping is unnecessary. Lines that genuinely overflow the visible width fall back to click’s implementation: the wrap point may still be sub-optimal but the output stays syntactically valid.

Note

Click 8.4.0 (PR pallets/click#3420) made click.formatting.TextWrapper ANSI-aware by counting visible width instead of raw bytes, so this override is a no-op fast path on Click >= 8.4.0 and only fixes wrapping on the Click 8.3.x releases click-extra still supports.

Todo

Drop this override once the minimum supported Click rises to 8.4.0 (which includes pallets/click#3420). The term_len-based visible-width check below becomes redundant once Click’s own wrapper counts visible width.

Return type:

None

keywords: HelpKeywords = HelpKeywords(cli_names=set(), subcommands=set(), command_aliases=set(), arguments=set(), long_options=set(), short_options=set(), choices=set(), choice_metavars=set(), metavars=set(), envvars=set(), defaults=set())
excluded_keywords: HelpKeywords | None = None
highlight_extra_keywords(help_text)[source]

Highlight extra keywords in help screens based on the theme.

Uses the highlight() function for all keyword categories. Each category is processed as a batch of regex patterns with a single styling function, which handles overlapping matches and prevents double-styling.

Return type:

str

getvalue()[source]

Wrap original Click.HelpFormatter.getvalue() to force extra-colorization on rendering.

Return type:

str

class click_extra.HelpKeywords(cli_names=<factory>, subcommands=<factory>, command_aliases=<factory>, arguments=<factory>, long_options=<factory>, short_options=<factory>, choices=<factory>, choice_metavars=<factory>, metavars=<factory>, envvars=<factory>, defaults=<factory>)[source]

Bases: object

Structured collection of keywords extracted from a Click context for help screen highlighting.

Each field corresponds to a semantic category with its own styling.

cli_names: set[str]
subcommands: set[str]
command_aliases: set[str]
arguments: set[str]
long_options: set[str]
short_options: set[str]
choices: set[str]
choice_metavars: set[str]
metavars: set[str]
envvars: set[str]
defaults: set[str]
merge(other)[source]

Merge another HelpKeywords into this one.

Each set field is updated with the corresponding set from other.

Return type:

None

subtract(other)[source]

Remove keywords found in other from this instance.

Each set field is difference-updated with the corresponding set from other. Mirror of merge().

Return type:

None

class click_extra.HelpSection(heading, definitions, help=None, constraint=None)[source]

Bases: object

A container for a help section data.

heading: str

Help section title.

definitions: Sequence[Tuple[str, str | Callable[[int], str]]]

Rows with 2 columns each. The 2nd element of each row can also be a function taking an integer (the available width for the 2nd column) and returning a string.

help: str | None = None

(Optional) long description of the section.

constraint: str | None = None

(Optional) option group constraint description.

class click_extra.HelpTheme(invoked_command=<function identity>, command_help=<function identity>, heading=<function identity>, constraint=<function identity>, section_help=<function identity>, col1=<function identity>, col2=<function identity>, alias=<function identity>, alias_secondary=None, epilog=<function identity>, critical=<function identity>, error=<function identity>, warning=<function identity>, info=<function identity>, debug=<function identity>, option=<function identity>, subcommand=<function identity>, choice=<function identity>, metavar=<function identity>, bracket=<function identity>, envvar=<function identity>, default=<function identity>, range_label=<function identity>, required=<function identity>, argument=<function identity>, deprecated=<function identity>, search=<function identity>, success=<function identity>, cross_ref_highlight=True, subheading=<function identity>)[source]

Bases: HelpTheme

Extends cloup.HelpTheme with slots for log levels and the structural elements Click Extra highlights in help screens.

Each slot below documents what it colors. The built-in themes shipped in BUILTIN_THEMES provide the visual styling by setting the relevant slots; user-defined themes can be authored as plain mappings and loaded via from_dict().

critical()

Style applied to the CRITICAL level name in log records.

Example: CRITICAL: Database connection lost.

Return type:

TypeVar(T)

error()

Style applied to the ERROR level name in log records.

Example: ERROR: Configuration file not found.

Return type:

TypeVar(T)

warning()

Style applied to the WARNING level name in log records.

Example: WARNING: Requested 16 jobs exceeds available CPU cores (8).

Return type:

TypeVar(T)

info()

Style applied to the INFO level name in log records.

Usually left at identity: INFO is the default verbosity and shouldn’t stand out from regular output.

Return type:

TypeVar(T)

debug()

Style applied to the DEBUG level name in log records.

Example: DEBUG: Resolved /etc/myapp/config.toml.

Return type:

TypeVar(T)

option()

Style applied to option names (--config, -v, --color/--no-color) wherever they appear: synopsis column, free-form descriptions, and docstrings (when cross_ref_highlight is enabled).

Return type:

TypeVar(T)

subcommand()

Style applied to subcommand names: in a group’s command list and wherever they are referenced in prose.

Return type:

TypeVar(T)

choice()

Style applied to each individual value inside a click.Choice metavar (like json, csv, xml within [json|csv|xml]) and to those values referenced in option descriptions.

Return type:

TypeVar(T)

metavar()

Style applied to type metavars (INTEGER, TEXT, PATH, FILE, …) that follow an option name in the synopsis column.

Return type:

TypeVar(T)

bracket()

Style applied to the literal bracket characters and label prefixes of trailing fields: [, ], default:, env var:, and the field separators between them. Also acts as the fallback for the four inner bracket-field slots (envvar, default, required, range_label) whenever any of them is left at identity. A theme that only sets bracket therefore renders the whole bracket field with a single uniform style; richer themes layer specific colors on top by setting the inner slots.

Return type:

TypeVar(T)

envvar()

Style applied to environment-variable values inside [env var: ...] bracket fields, and to envvar names mentioned in option descriptions. Falls back to bracket when left at identity, so a theme that only styles bracket still gets a consistent rendering inside bracket fields.

Return type:

TypeVar(T)

default()

Style applied to the default-value content inside [default: ...] bracket fields. Falls back to bracket when left at identity.

Return type:

TypeVar(T)

range_label()

Style applied to range expressions (0<=x<=9, x>=1024, 0<=x<100) that appear inside bracket fields for IntRange and FloatRange options. Falls back to bracket when left at identity.

Return type:

TypeVar(T)

required()

Style applied to the required label inside bracket fields on mandatory options. Falls back to bracket when left at identity.

Return type:

TypeVar(T)

argument()

Style applied to argument metavars (positional parameter names like MY_ARG, SCRIPT, [FILENAMES]...) in the synopsis column and when referenced in prose.

Return type:

TypeVar(T)

deprecated()

Style applied to (DEPRECATED) / (Deprecated: reason) markers appended to options and commands.

Return type:

TypeVar(T)

search()

Style applied to substring matches in <cli> help --search output, so users can spot where their query matched.

Return type:

TypeVar(T)

success()

Style applied to success glyphs in pre-rendered UI elements (the in OK_GLYPH) and any text passed through this slot by downstream code.

Return type:

TypeVar(T)

cross_ref_highlight: bool = True

Highlight options, choices, arguments, metavars and CLI names in free-form text (descriptions, docstrings).

When False, only structural elements are styled: bracket fields ([default: ...], [env var: ...], ranges, [required]), deprecated messages, and subcommand names in definition lists.

subheading()

Style for sub-section headings inside log output or inline help.

Distinct from heading (which styles the top-level help-screen section titles): subheading is intended for downstream code that wants a second styling level for its own narrative output.

See also

Used by mail-deduplicate to style N mails sharing hash log lines.

Return type:

TypeVar(T)

with_(**kwargs)[source]

Derives a new theme from the current one, with some styles overridden.

Returns the same instance if the provided styles are the same as the current.

Return type:

HelpTheme

to_dict()[source]

Serialize the theme to a plain dict suitable for TOML/JSON/YAML.

Each Style slot is emitted via Style.to_dict. Slots left at their default (identity or None) are omitted, so the output only carries what the theme actually overrides. Pair with from_dict() to round-trip.

Raises:

TypeError – when a slot holds an opaque IStyle callable that is not a Style (those cannot be serialized).

Return type:

dict[str, Any]

classmethod from_dict(data)[source]

Build a theme from the plain dict produced by to_dict().

Each value is interpreted by field type: a mapping becomes a Style via Style.from_dict, while cross_ref_highlight is read as a plain bool. Unknown keys raise TypeError so typos surface immediately.

Return type:

HelpTheme

cascade(base)[source]

Layer this theme’s set slots on top of base.

Mirrors Style.cascade at the slot level: this theme’s non-default slots win, base fills the rest. Useful for layering a sparse override (typically parsed from a config file’s [tool.<cli>.themes.<name>] table) on top of a full built-in palette.

Raises:

TypeError – when base is not a HelpTheme.

Return type:

HelpTheme

class click_extra.IntRange(min=None, max=None, min_open=False, max_open=False, clamp=False)[source]

Bases: _NumberRangeBase[int], IntParamType

Restrict an click.INT value to a range of accepted values. See Int and Float Ranges.

If min or max are not passed, any value is accepted in that direction. If min_open or max_open are enabled, the corresponding boundary is not included in the range.

If clamp is enabled, a value outside the range is clamped to the boundary instead of failing.

Changed in version 8.0: Added the min_open and max_open parameters.

name: str = 'integer range'

the descriptive name of this type

class click_extra.JobsOption(param_decls=None, default='auto', expose_value=False, show_default=True, type=<click_extra.execution.JobCount object>, help="Number of parallel jobs. Accepts an integer, 'auto' (one fewer than the host's logical CPUs) or 'max' (all logical CPUs). 0 runs sequentially.", **kwargs)[source]

Bases: ExtraOption

A pre-configured --jobs option to control parallel execution.

Accepts an integer or one of two keywords resolved by JobCount: auto (the default: one fewer than the available logical CPU cores, leaving a core free for the main process and system tasks) and max (every available logical CPU core). A value of 0 disables parallelism and runs sequentially.

The core count is the number of logical CPUs (hardware threads) reported by os.cpu_count(), not physical cores: see CPU_COUNT. On a host with too few logical CPUs, auto/max resolve to a single job and JobCount logs a warning that execution will be sequential.

The resolved value is stored as an int in ctx.meta[click_extra.context.JOBS].

Warning

JobsOption only resolves and publishes the job count: it does not drive any concurrency by itself. Pass it to run_jobs() (which reads the resolved ctx.meta[click_extra.context.JOBS] count), or read that value yourself and act on it.

validate_jobs(ctx, param, value)[source]

Validate the resolved job count and store it in context metadata.

JobCount has already resolved any auto/max keyword to an integer by the time this runs. A value of 0 disables parallelism: it is rounded up to 1 (sequential execution) with a warning. Negative values are likewise clamped to 1, and a count above the available cores is honored but warned about. The resolved count is then logged at info level next to the host’s logical CPU count (CPU_COUNT), so a CLI’s parallelism is visible under --verbosity INFO.

Return type:

None

class click_extra.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"}
list_commands(ctx)[source]

List all commands, including not-yet-loaded lazy subcommands.

Return type:

list[str]

get_command(ctx, cmd_name)[source]

Get a command by name, loading lazily if necessary.

Todo

Allow passing extra parameters to the self.lazy_subcommands so we can register commands with custom settings like Cloup’s section or fallback_to_default_section:

  • section: Section | None = None,

  • fallback_to_default_section: bool = True,

See: https://github.com/janluke/cloup/blob/master/cloup/_sections.py#L169

Return type:

Command | None

class click_extra.LogLevel(*values)[source]

Bases: IntEnum

Mapping of canonical log level names to their integer level.

That’s our own version of logging._nameToLevel, but:

CRITICAL = 50
ERROR = 40
WARNING = 30
INFO = 20
DEBUG = 10
class click_extra.ManOption(param_decls=None, is_flag=True, expose_value=False, is_eager=True, help="Show the command's man page (roff) and exit.", **kwargs)[source]

Bases: ExtraOption

A pre-configured --man flag that prints the command’s man page (roff) to stdout and exits.

Eager and value-less, like ShowParamsOption. Part of the default option set injected by default_params(), so every @command and @group exposes it. Use @man_option to add it to a plain Click CLI.

Note

The flag is named --man, not --show-man or --man-page.

In the POSIX, GNU and BSD traditions a program does not emit its own man page through a flag: the page is a separate file read with man <prog>, either hand-written (BSD mdoc) or generated at build time from --help output (GNU help2man). Click Extra already covers that build-time path with write_manpages(), its help2man equivalent.

The one ecosystem that exposes a runtime flag is Perl’s Pod::Usage, whose convention is --help for the brief usage and bare --man for the full manual. --man also lines up with the neighbouring --help and --version informational flags, which use bare nouns with no show- prefix. --show-man and --man-page have no precedent outside Click Extra.

print_man(ctx, param, value)[source]

Render and print the invoked command’s man page, then exit.

Return type:

None

class click_extra.ManPage(name, short_help='', section='1', synopsis_pieces=(), description='', operands=(), option_groups=(), subcommands=(), environment=(), files=(), exit_status=(('0', 'Success.'), ('1', 'A runtime error, or an aborted prompt (Ctrl-C, a declined confirmation).'), ('2', 'A usage error: unknown option, invalid value, missing operand, or an unparsable configuration file.')), version=None, date='', manual=None, authors=None, copyright=None)[source]

Bases: object

A whole man page in structured form, ready to render to roff.

One ManPage maps to one command (or subcommand). Its fields are the man-pages(7) sections, in the order Man-page documents them. Build it with extract_manpage() and serialize with to_roff().

name: str

Full command path, space-joined (like weather forecast).

short_help: str = ''

One-line description for the NAME section.

section: str = '1'

Man section number.

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

Usage metavars after the command name ([OPTIONS], CITY, …).

description: str = ''

The command’s full help text / docstring for the DESCRIPTION section.

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

Positional arguments as (metavar, help) pairs.

option_groups: tuple[ManOptionGroup, ...] = ()

The OPTIONS entries, partitioned into one or more groups. A command without explicit option groups carries a single untitled group.

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

For groups: (name, short_help) pairs for the COMMANDS section.

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

ENVIRONMENT entries as (variable_name, help) pairs.

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

FILES entries (configuration search patterns).

exit_status: tuple[tuple[str, str], ...] = (('0', 'Success.'), ('1', 'A runtime error, or an aborted prompt (Ctrl-C, a declined confirmation).'), ('2', 'A usage error: unknown option, invalid value, missing operand, or an unparsable configuration file.'))

EXIT STATUS entries as (code, meaning) pairs.

version: str | None = None

Version string for the .TH header.

date: str = ''

Date for the .TH header (YYYY-MM-DD).

manual: str | None = None

Manual name for the .TH header (the centered footer title).

authors: str | None = None

AUTHORS section content, or None to omit the section.

copyright: str | None = None

COPYRIGHT section content, or None to omit the section.

property title: str

The .TH page title: the command path, hyphen-joined and upper-cased.

to_roff()[source]

Render the full man page as a roff/troff string.

Return type:

str

exception click_extra.MissingParameter(message=None, ctx=None, param=None, param_hint=None, param_type=None)[source]

Bases: BadParameter

Raised if click required an option or argument but it was not provided when invoking the script.

Added in version 4.0.

Parameters:

param_type (str | None) – a string that indicates the type of the parameter. The default is to inherit the parameter type from the given param. Valid values are 'parameter', 'option' or 'argument'.

format_message()[source]
Return type:

str

class click_extra.MultiChoice(choices=(), separator=',', case_sensitive=True)[source]

Bases: ParamType

Comma-separated multi-pick from a fixed set of values.

The pick-many counterpart to click.Choice. Accepts a single token containing several values joined by a configurable separator (defaults to ,), parses it into a tuple[str, ...] and validates each value against choices when that set is non-empty.

The rendered metavar is [a,b,c] (separator-joined, parallel to Choice’s [a|b|c]): click_extra.highlight._HelpColorsMixin auto-detects the separator and highlights each individual value the same way it does for Choice.

Note

Click does not ship a built-in equivalent. The closest idiomatic approach is click.Choice([...]) + multiple=True, which requires the flag to be repeated (--tag a --tag b --tag c) rather than comma-separated. The lack of a single-token, separator-based variant upstream has been raised in:

  • pallets/click#2771 (open): request for nargs=-1 with a non-whitespace separator, covering exactly this use case.

  • pallets/click#2537 (closed as not planned): earlier request for space-separated multi values via nargs=-1 on options.

Maintainers have leaned on the orthogonality argument: multiple=True already exists, separator conventions vary across communities (, vs. : vs. ;), and escaping breaks down when a value contains the chosen separator. MultiChoice ships the convention anyway because SQL-style SELECT a, b, c syntax reads more naturally for the tabular use cases click-extra supports (click_extra.table.ColumnsOption is the headline consumer).

Initialize the type.

Parameters:
  • choices (Sequence[str]) – the accepted values. When non-empty, convert() rejects unknown tokens with fail. When empty, the type behaves as a pure separator-aware parser and leaves validation to the consumer.

  • separator (str) – the token boundary. Use any single character; this also drives the metavar rendering ([a<sep>b<sep>c]).

  • case_sensitive (bool) – when False, tokens match choices case-insensitively and the returned tuple holds the canonical (original-case) values from choices.

name: str = 'multi'

the descriptive name of this type

choices: tuple[str, ...]
separator: str
case_sensitive: bool
get_metavar(param, ctx=None)[source]

Render [a<sep>b<sep>c] when choices is set, None otherwise.

None falls back to Click’s default rendering (the uppercased name, like MULTI).

convert(value, param, ctx)[source]

Split value on separator and validate each token.

Already-parsed tuples and lists are returned unchanged so defaults declared as tuples flow through untouched. Empty tokens (consecutive separators, trailing separator) are dropped silently.

Return type:

tuple[str, ...]

class click_extra.NoColorOption(param_decls=None, is_flag=True, default=False, is_eager=True, expose_value=False, help='Disable colorization (alias of --color=never).', **kwargs)[source]

Bases: ExtraOption

--no-color flag that forces --color=never.

Click rejects /--no-x secondary flags on a value option, so the negative alias of the tri-state ColorOption cannot live on it and is provided here as a standalone boolean flag. When set, it pins ctx.color to False; when absent it is a no-op, leaving the resolution to ColorOption.

Shown on its own line directly below --color (mirroring --no-config below --config), since every other negative in the default option set is visible too. Eager by default, like ColorOption, so the color state is settled before other eager options render.

set_no_color(ctx, param, value)[source]

Force ctx.color off when a negative alias is passed; no-op otherwise.

Return type:

None

class click_extra.NoConfigOption(param_decls=None, type=UNPROCESSED, help='Ignore all configuration files and only use command line parameters and environment variables.', is_flag=True, flag_value=Sentinel.NO_CONFIG, is_eager=True, expose_value=False, **kwargs)[source]

Bases: ExtraOption

A pre-configured option adding --no-config.

This option is supposed to be used alongside the --config option (ConfigOption) to allow users to explicitly disable the use of any configuration file.

This is especially useful to debug side-effects caused by autodetection of configuration files.

flag_value=NO_CONFIG is the Sentinel enum member that signals “skip configuration loading” to ConfigOption. Click 8.4.0 (PR pallets/click#3363) auto-detects type=UNPROCESSED for non-basic flag_value types, but click-extra still supports Click 8.3.x where that auto-detection is absent, so the type=UNPROCESSED override is kept explicit to let the sentinel pass through Option unchanged on every supported Click.

See also

An alternative implementation of this class would be to create a custom click.ParamType instead of a custom Option subclass. Here is for example.

check_sibling_config_option(ctx, param, value)[source]

Ensure that this option is used alongside a ConfigOption instance.

Return type:

None

exception click_extra.NoSuchCommand(command_name, message=None, possibilities=None, ctx=None)[source]

Bases: UsageError

Raised if Click attempted to handle a command that does not exist.

Added in version 8.4.0.

possibilities: list[str] | None
format_message()[source]
Return type:

str

exception click_extra.NoSuchOption(option_name, message=None, possibilities=None, ctx=None)[source]

Bases: UsageError

Raised if Click attempted to handle an option that does not exist.

Added in version 4.0.

possibilities: list[str] | None
format_message()[source]
Return type:

str

class click_extra.Option(*args, group=None, **attrs)[source]

Bases: _ParameterMixin, Option

Wrap cloup.Option, itself inheriting from click.Option.

Inherits first from _ParameterMixin to allow future overrides of Click’s Parameter methods.

class click_extra.OptionGroup(title, help=None, constraint=None, hidden=False)[source]

Bases: object

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.

property options: Sequence[Option]
get_help_records(ctx)[source]
Return type:

List[Tuple[str, str]]

option(*param_decls, **attrs)[source]

Refer to cloup.option().

Return type:

Callable[[TypeVar(F, bound= Callable[..., Any])], TypeVar(F, bound= Callable[..., Any])]

class click_extra.OptionGroupMixin(*args, align_option_groups=None, **kwargs)[source]

Bases: object

Implements support for:

  • option groups

  • the “Positional arguments” help section; this section is shown only if at least one of your arguments has non-empty help.

Important

In order to check the constraints defined on the option groups, a command must inherits from cloup.ConstraintMixin too!

Added in version 0.14.0: added the “Positional arguments” help section.

Changed in version 0.8.0: this mixin now relies on cloup.HelpFormatter to align help sections. If a click.HelpFormatter is used with a TypeError is raised.

Changed in version 0.8.0: removed format_option_group. Added get_default_option_group and make_option_group_help_section.

Added in version 0.5.0.

Parameters:
  • align_option_groups (bool | None) – whether to align the columns of all option groups’ help sections. This is also available as a context setting having a lower priority than this attribute. Given that this setting should be consistent across all you commands, you should probably use the context setting only.

  • args (Any) – positional arguments forwarded to the next class in the MRO

  • kwargs (Any) – keyword arguments forwarded to the next class in the MRO

option_groups

List of all option groups, except the “default option group”.

ungrouped_options

List of options not explicitly assigned to an user-defined option group. These options will be included in the “default option group”. Note: this list does not include options added automatically by Click based on context settings, like the --help option; use the get_ungrouped_options() method if you need the real full list (which needs a Context object).

get_ungrouped_options(ctx)[source]

Return options not explicitly assigned to an option group (eventually including the --help option), i.e. options that will be part of the “default option group”.

Return type:

Sequence[Option]

get_argument_help_record(arg, ctx)[source]
Return type:

Tuple[str, str]

get_arguments_help_section(ctx)[source]
Return type:

HelpSection | None

make_option_group_help_section(group, ctx)[source]

Return a HelpSection for an OptionGroup, i.e. an object containing the title, the optional description and the options’ definitions for this option group.

Added in version 0.8.0.

Return type:

HelpSection

must_align_option_groups(ctx, default=True)[source]

Return True if the help sections of all options groups should have their columns aligned.

Added in version 0.8.0.

Return type:

bool

get_default_option_group(ctx, is_the_only_visible_option_group=False)[source]

Return an OptionGroup instance for the options not explicitly assigned to an option group, eventually including the --help option.

Added in version 0.8.0.

Return type:

OptionGroup

format_params(ctx, formatter)[source]
Return type:

None

class click_extra.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.

included_params: frozenset[str] | None

Allowlist of parameter IDs, mutually exclusive with excluded_params.

None disables the allowlist. It is resolved into excluded_params by build_param_trees(), once every parameter ID is known.

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

Utility method to recursively create a nested dict structure whose keys are provided by path list and at the end is populated by a copy of leaf.

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()[source]

Generate an unfiltered list of all CLI parameters.

Everything is included, from top-level groups to subcommands, and from options to arguments.

Return type:

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

Yields a 2-element tuple:
  • a tuple of keys leading to the parameter;

  • the parameter object itself.

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

See the list of custom types provided by Click.

Return type:

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

build_param_trees()[source]

Build the parameters tree structure and cache it.

This removes parameters whose fully-qualified IDs are in the excluded_params blocklist.

If included_params was provided, it is resolved into excluded_params here, where all parameter IDs are available.

Return type:

None

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.

class click_extra.ParamType[source]

Bases: Generic[ParamTypeValue], ABC

Represents the type of a parameter. Validates and converts values from the command line or Python into the correct type.

To implement a custom type, subclass and implement at least the following:

  • The name class attribute must be set.

  • Calling an instance of the type with None must return None. This is already implemented by default.

  • convert() must convert string values to the correct type.

  • convert() must accept values that are already the correct type.

  • It must be able to convert a value if the ctx and param arguments are None. This can occur when converting prompt input.

Changed in version 8.4.0: Now a generic abstract base class. Parameterize with the converted value type (ParamType[int] for an integer-returning type) so that convert() and downstream consumers carry the narrowed return type.

is_composite: ClassVar[bool] = False
arity: ClassVar[int] = 1
name: str

the descriptive name of this type

envvar_list_splitter: ClassVar[str | None] = None

if a list of this type is expected and the value is pulled from a string environment variable, this is what splits it up. None means any whitespace. For all parameters the general rule is that whitespace splits them up. The exception are paths and files which are split by os.path.pathsep by default (“:” on Unix and “;” on Windows).

to_info_dict()[source]

Gather information that could be useful for a tool generating user-facing documentation.

Use click.Context.to_info_dict() to traverse the entire CLI structure.

Added in version 8.0.

Return type:

ParamTypeInfoDict

get_metavar(param, ctx)[source]

Returns the metavar default for this param if it provides one.

Return type:

str | None

get_missing_message(param, ctx)[source]

Optionally might return extra information about a missing parameter.

Added in version 2.0.

Return type:

str | None

convert(value, param, ctx)[source]

Convert the value to the correct type. This is not called if the value is None (the missing value).

This must accept string values from the command line, as well as values that are already the correct type. It may also convert other compatible types.

The param and ctx arguments may be None in certain situations, such as when converting prompt input.

If the value cannot be converted, call fail() with a descriptive message.

Parameters:
  • value (t.Any) – The value to convert.

  • param (Parameter | None) – The parameter that is using this type to convert its value. May be None.

  • ctx (Context | None) – The current context that arrived at this value. May be None.

Return type:

ParamTypeValue

split_envvar_value(rv)[source]

Given a value from an environment variable this splits it up into small chunks depending on the defined envvar list splitter.

If the splitter is set to None, which means that whitespace splits, then leading and trailing whitespace is ignored. Otherwise, leading and trailing splitters usually lead to empty items being included.

Return type:

Sequence[str]

fail(message, param=None, ctx=None)[source]

Helper method to fail with an invalid value message.

Return type:

t.NoReturn

shell_complete(ctx, param, incomplete)[source]

Return a list of CompletionItem objects for the incomplete value. Most types do not provide completions, but some do, and this allows custom types to provide custom completions as well.

Parameters:
  • ctx (Context) – Invocation context for this command.

  • param (Parameter) – The parameter that is requesting completion.

  • incomplete (str) – Value being completed. May be empty.

Added in version 8.0.

Return type:

list[CompletionItem]

class click_extra.Parameter(param_decls=None, type=None, required=False, default=Sentinel.UNSET, callback=None, nargs=None, multiple=False, metavar=None, expose_value=True, is_eager=False, envvar=None, shell_complete=None, deprecated=False)[source]

Bases: ABC

A parameter to a command comes in two versions: they are either Options or Arguments. Other subclasses are currently not supported by design as some of the internals for parsing are intentionally not finalized.

Some settings are supported by both options and arguments.

Parameters:
  • param_decls (cabc.Sequence[str] | None) – the parameter declarations for this option or argument. This is a list of flags or argument names.

  • type (types.ParamType[t.Any] | t.Any | None) – the type that should be used. Either a ParamType or a Python type. The latter is converted into the former automatically if supported.

  • required (bool) – controls if this is optional or not.

  • default (t.Any | t.Callable[[], t.Any] | None) – the default value if omitted. This can also be a callable, in which case it’s invoked when the default is needed without any arguments.

  • callback (t.Callable[[Context, Parameter, t.Any], t.Any] | None) – A function to further process or validate the value after type conversion. It is called as f(ctx, param, value) and must return the value. It is called for all sources, including prompts.

  • nargs (int | None) – the number of arguments to match. If not 1 the return value is a tuple instead of single value. The default for nargs is 1 (except if the type is a tuple, then it’s the arity of the tuple). If nargs=-1, all remaining parameters are collected.

  • metavar (str | None) – how the value is represented in the help page.

  • expose_value (bool) – if this is True then the value is passed onwards to the command callback and stored on the context, otherwise it’s skipped.

  • is_eager (bool) – eager values are processed before non eager ones. This should not be set for arguments or it will inverse the order of processing.

  • envvar (str | cabc.Sequence[str] | None) – environment variable(s) that are used to provide a default value for this parameter. This can be a string or a sequence of strings. If a sequence is given, only the first non-empty environment variable is used for the parameter.

  • shell_complete (t.Callable[[Context, Parameter, str], list[CompletionItem] | list[str]] | None) – A function that returns custom shell completions. Used instead of the param’s type completion if given. Takes ctx, param, incomplete and must return a list of CompletionItem or a list of strings.

  • deprecated (bool | str) – If True or non-empty string, issues a message indicating that the argument is deprecated and highlights its deprecation in –help. The message can be customized by using a string as the value. A deprecated parameter cannot be required, a ValueError will be raised otherwise.

Changed in version 8.2.0: Introduction of deprecated.

Changed in version 8.2: Adding duplicate parameter names to a Command will result in a UserWarning being shown.

Changed in version 8.2: Adding duplicate parameter names to a Command will result in a UserWarning being shown.

Changed in version 8.0: process_value validates required parameters and bounded nargs, and invokes the parameter callback before returning the value. This allows the callback to validate prompts. full_process_value is removed.

Changed in version 8.0: autocompletion is renamed to shell_complete and has new semantics described above. The old name is deprecated and will be removed in 8.1, until then it will be wrapped to match the new requirements.

Changed in version 8.0: For multiple=True, nargs>1, the default must be a list of tuples.

Changed in version 8.0: Setting a default is no longer required for nargs>1, it will default to None. multiple=True or nargs=-1 will default to ().

Changed in version 7.1: Empty environment variables are ignored rather than taking the empty string value. This makes it possible for scripts to clear variables if they can’t unset them.

Changed in version 2.0: Changed signature for parameter callback to also be passed the parameter. The old callback format will still work, but it will raise a warning to give you a chance to migrate the code easier.

param_type_name = 'parameter'
name: str
opts: list[str]
secondary_opts: list[str]
type: ParamType[Any]
default: Any | Callable[[], Any] | None
to_info_dict()[source]

Gather information that could be useful for a tool generating user-facing documentation.

Use click.Context.to_info_dict() to traverse the entire CLI structure.

Changed in version 8.3.0: Returns None for the default if it was not set.

Added in version 8.0.

Return type:

dict[str, Any]

property human_readable_name: str

Returns the human readable name of this parameter. This is the same as the name for options, but the metavar for arguments.

make_metavar(ctx)[source]
Return type:

str

get_default(ctx, call=True)[source]
Overloads:
  • self, ctx (Context), call (t.Literal[True]) → t.Any | None

  • self, ctx (Context), call (bool) → t.Any | t.Callable[[], t.Any] | None

Get the default for the parameter. Tries Context.lookup_default() first, then the local default.

Parameters:
  • ctx (Context) – Current context.

  • call (bool) – If the default is a callable, call it. Disable to return the callable instead.

Changed in version 8.0.2: Type casting is no longer performed when getting a default.

Changed in version 8.0.1: Type casting can fail in resilient parsing mode. Invalid defaults will not prevent showing help text.

Changed in version 8.0: Looks at ctx.default_map first.

Changed in version 8.0: Added the call parameter.

abstractmethod add_to_parser(parser, ctx)[source]
Return type:

None

type_cast_value(ctx, value)[source]

Convert and validate a value against the parameter’s type, multiple, and nargs.

Return type:

Any

get_help_record(ctx)[source]
Return type:

tuple[str, str] | None

get_usage_pieces(ctx)[source]
Return type:

list[str]

get_error_hint(ctx)[source]

Get a stringified version of the param for use in error messages to indicate which param caused the error.

Changed in version 8.4.0: ctx can be None.

Return type:

str

shell_complete(ctx, incomplete)[source]

Return a list of completions for the incomplete value. If a shell_complete function was given during init, it is used. Otherwise, the type shell_complete() function is used.

Parameters:
  • ctx (Context) – Invocation context for this command.

  • incomplete (str) – Value being completed. May be empty.

Added in version 8.0.

Return type:

list[CompletionItem]

class click_extra.ParameterSource(*values)[source]

Bases: IntEnum

This is an IntEnum that indicates the source of a parameter’s value.

Use click.Context.get_parameter_source() to get the source for a parameter by name.

Members are ordered from most explicit to least explicit source. This allows comparison to check if a value was explicitly provided:

source = ctx.get_parameter_source("port")
if source < click.ParameterSource.DEFAULT_MAP:
    ...  # value was explicitly set

Changed in version 8.3.3: Use IntEnum and reorder members from most to least explicit. Supports comparison operators.

Changed in version 8.0: Use Enum and drop the validate method.

Changed in version 8.0: Added the PROMPT value.

PROMPT = 1

Used a prompt to confirm a default or provide a value.

COMMANDLINE = 2

The value was provided by the command line args.

ENVIRONMENT = 3

The value was provided with an environment variable.

DEFAULT_MAP = 4

Used a default provided by Context.default_map.

DEFAULT = 5

Used the default specified by the parameter.

class click_extra.Path(exists=False, file_okay=True, dir_okay=True, writable=False, readable=True, resolve_path=False, allow_dash=False, path_type=None, executable=False)[source]

Bases: ParamType[str | bytes | PathLike[str]]

The Path type is similar to the File type, but returns the filename instead of an open file. Various checks can be enabled to validate the type of file and permissions.

Parameters:
  • exists (bool) – The file or directory needs to exist for the value to be valid. If this is not set to True, and the file does not exist, then all further checks are silently skipped.

  • file_okay (bool) – Allow a file as a value.

  • dir_okay (bool) – Allow a directory as a value.

  • readable (bool) – if true, a readable check is performed.

  • writable (bool) – if true, a writable check is performed.

  • executable (bool) – if true, an executable check is performed.

  • resolve_path (bool) – Make the value absolute and resolve any symlinks. A ~ is not expanded, as this is supposed to be done by the shell only.

  • allow_dash (bool) – Allow a single dash as a value, which indicates a standard stream (but does not open it). Use open_file() to handle opening this value.

  • path_type (type[Any] | None) – Convert the incoming path value to this type. If None, keep Python’s default, which is str. Useful to convert to pathlib.Path.

Changed in version 8.1: Added the executable parameter.

Changed in version 8.0: Allow passing path_type=pathlib.Path.

Changed in version 6.0: Added the allow_dash parameter.

envvar_list_splitter: ClassVar[str] = ':'

if a list of this type is expected and the value is pulled from a string environment variable, this is what splits it up. None means any whitespace. For all parameters the general rule is that whitespace splits them up. The exception are paths and files which are split by os.path.pathsep by default (“:” on Unix and “;” on Windows).

name: str

the descriptive name of this type

to_info_dict()[source]

Gather information that could be useful for a tool generating user-facing documentation.

Use click.Context.to_info_dict() to traverse the entire CLI structure.

Added in version 8.0.

Return type:

PathInfoDict

coerce_path_result(value)[source]
Return type:

str | bytes | PathLike[str]

convert(value, param, ctx)[source]

Convert the value to the correct type. This is not called if the value is None (the missing value).

This must accept string values from the command line, as well as values that are already the correct type. It may also convert other compatible types.

The param and ctx arguments may be None in certain situations, such as when converting prompt input.

If the value cannot be converted, call fail() with a descriptive message.

Parameters:
  • value (str | os.PathLike[str]) – The value to convert.

  • param (Parameter | None) – The parameter that is using this type to convert its value. May be None.

  • ctx (Context | None) – The current context that arrived at this value. May be None.

Return type:

str | bytes | os.PathLike[str]

shell_complete(ctx, param, incomplete)[source]

Return a special completion marker that tells the completion system to use the shell to provide path completions for only directories or any paths.

Parameters:
  • ctx (Context) – Invocation context for this command.

  • param (Parameter) – The parameter that is requesting completion.

  • incomplete (str) – Value being completed. May be empty.

Added in version 8.0.

Return type:

list[CompletionItem]

class click_extra.PrebakeConfig(module=None)[source]

Bases: object

Config schema for the prebake commands, read from [tool.<cli>.prebake].

Lets a project pin the target __init__.py once for its build pipeline, instead of passing --module to every click-extra prebake command.

module: str | None = None

Path to the __init__.py to pre-bake, resolved relative to the project root. Overrides the [project.scripts] auto-discovery; leave unset to keep it.

class click_extra.ProgressOption(param_decls=None, is_flag=True, default=True, is_eager=True, expose_value=False, help='Show progress indicators during long operations. Disabled for non-interactive output (pipes, dumb terminals, CI) and by --accessible.', **kwargs)[source]

Bases: ExtraOption

A pre-configured --progress/--no-progress flag gating spinner display.

Resolves to a single boolean published at ctx.meta[click_extra.context.PROGRESS], which a CLI reads to decide whether to start a Spinner. The default is True; --accessible lowers it to False (via default_map) so a screen reader is never handed a spinning glyph.

Note

Spinner display is intentionally decoupled from color, even though both emit ANSI. A spinner is an interactivity concern, not a color one: it is built from cursor-control codes (hide-cursor, carriage return, clear-line), which the NO_COLOR standard explicitly does not govern – it “only signals the user’s intention regarding adding ANSI color to text output”. So --no-color / NO_COLOR strip the spinner’s colors but never hide it.

This matches how the wider ecosystem treats the two axes as orthogonal: cargo, npm, pip, Rich, indicatif and ora all gate progress on the terminal (and a dedicated --progress/--quiet knob), while NO_COLOR only affects color. Rich uses TERM=dumb – not NO_COLOR – as the signal to drop cursor-moving features like progress bars.

The spinner is therefore silenced by two things only, neither of them color:

  • non-interactive output – a pipe, file, CI log, or TERM=dumb terminal that cannot move the cursor (see Spinner._resolve_enabled);

  • explicit intent--no-progress or --accessible.

This option is eager. It no longer reads ctx.color, so its position relative to ColorOption is not load-bearing.

set_progress(ctx, param, value)[source]

Publish whether progress spinners may be shown.

Stores the resolved --progress flag at PROGRESS. Deliberately independent of color: see the ProgressOption note for why a spinner is gated on interactivity (TTY / TERM=dumb) and --accessible, never on --no-color / NO_COLOR.

Return type:

None

class click_extra.QuietOption(param_decls=None, count=True, **kwargs)[source]

Bases: _VerbosityOption

--quiet/-q option to lower the log level of _VerbosityOption by one step per repetition.

The symmetric counterpart of VerboseOption: where -v raises the verbosity one LogLevel step at a time, -q lowers it. Starting from VerbosityOption.default (WARNING by default):

  • -q lowers the level to ERROR,

  • -qq lowers the level to CRITICAL,

  • any further repetition is clamped at the quietest level, so -qqqqq for example resolves to CRITICAL.

-q shares a single signed counter with VerboseOption’s -v, so the two cancel out: -v -q leaves the level unchanged. See _VerbosityOption.resolve_level for the full reconciliation rule with --verbosity.

Set up a verbosity-altering option.

Parameters:

default_logger – If a logging.Logger object is provided, that’s the instance to which we will set the level to. If the parameter is a string and is found in the global registry, we will use it as the logger’s ID. Otherwise, we will create a new logger with new_logger() Default to the global root logger.

set_level(ctx, param, value)[source]

Record the -q repetition count, then reconcile.

The number of repetitions is saved in ctx.meta[click_extra.context.QUIET] and folded into the verbosity counter by _VerbosityOption.resolve_level.

Return type:

None

class click_extra.Result(runner, stdout_bytes, stderr_bytes, output_bytes, return_value, exit_code, exception, exc_info=None)[source]

Bases: Result

A Result subclass with automatic traceback formatting.

Enhances __repr__ so that pytest assertion failures show the full traceback instead of just the exception type.

property formatted_exception: str | None[source]

Full formatted traceback, or None if no exception occurred.

class click_extra.Section(title, commands=(), is_sorted=False)[source]

Bases: object

A group of (sub)commands to show in the same help section of a MultiCommand. You can use sections with any Command that inherits from SectionMixin.

Changed in version 0.6.0: removed the deprecated old name GroupSection.

Changed in version 0.5.0: introduced the new name Section and deprecated the old GroupSection.

Parameters:
  • title (str)

  • commands (Iterable[Command] | Dict[str, Command]) – sequence of commands or dict of commands keyed by name

  • is_sorted (bool) – if True, list_commands() returns the commands in lexicographic order

classmethod sorted(title, commands=())[source]
Return type:

Section

add_command(cmd, name=None)[source]
Return type:

None

list_commands()[source]
Return type:

List[Tuple[str, Command]]

class click_extra.SectionMixin(*args, commands=None, sections=(), align_sections=None, **kwargs)[source]

Bases: object

Adds to a click.MultiCommand the possibility of organizing its subcommands into multiple help sections.

Sections can be specified in the following ways:

  1. passing a list of Section objects to the constructor setting the argument sections

  2. using add_section() to add a single section

  3. using add_command() with the argument section set

Commands not assigned to any user-defined section are added to the “default section”, whose title is “Commands” or “Other commands” depending on whether it is the only section or not. The default section is the last shown section in the help and its commands are listed in lexicographic order.

Changed in version 0.8.0: this mixin now relies on cloup.HelpFormatter to align help sections. If a click.HelpFormatter is used with a TypeError is raised.

Changed in version 0.8.0: removed format_section. Added make_commands_help_section.

Added in version 0.5.0.

Parameters:
  • align_sections (bool | None) – whether to align the columns of all subcommands’ help sections. This is also available as a context setting having a lower priority than this attribute. Given that this setting should be consistent across all you commands, you should probably use the context setting only.

  • args (Any) – positional arguments forwarded to the next class in the MRO

  • kwargs (Any) – keyword arguments forwarded to the next class in the MRO

add_section(section)[source]

Add a Section to this group. You can add the same section object only a single time.

Return type:

None

See Also:

section()

section(title, *commands, **attrs)[source]

Create a new Section, adds it to this group and returns it.

Return type:

Section

add_command(cmd, name=None, section=None, fallback_to_default_section=True)[source]

Add a subcommand to this Group.

Implementation note: fallback_to_default_section looks not very clean but, even if it’s not immediate to see (it wasn’t for me), I chose it over apparently cleaner options.

Parameters:
  • cmd (Command)

  • name (str | None)

  • section (Section | None) – a Section instance. The command must not be in the section already.

  • fallback_to_default_section (bool) – if section is None and this option is enabled, the command is added to the “default section”. If disabled, the command is not added to any section unless section is provided. This is useful for internal code and subclasses. Don’t disable it unless you know what you are doing.

Return type:

None

list_sections(ctx, include_default_section=True)[source]

Return the list of all sections in the “correct order”.

If include_default_section=True and the default section is non-empty, it will be included at the end of the list.

Return type:

List[Section]

format_subcommand_name(ctx, name, cmd)[source]

Used to format the name of the subcommands. This method is useful when you combine this extension with other click extensions that override format_commands(). Most of these, like click-default-group, just add something to the name of the subcommands, which is exactly what this method allows you to do without overriding bigger methods.

Return type:

str

make_commands_help_section(ctx, section)[source]
Return type:

HelpSection | None

must_align_sections(ctx, default=True)[source]
Return type:

bool

format_commands(ctx, formatter)[source]
Return type:

None

class click_extra.ShowParamsOption(param_decls=None, is_flag=True, expose_value=False, is_eager=True, help='Show all CLI parameters, their provenance, defaults and value, then exit.', **kwargs)[source]

Bases: ExtraOption, ParamStructure

A pre-configured option adding a --show-params option.

Between configuration files, default values and environment variables, it might be hard to guess under which set of parameters the CLI will be executed. This option print information about the parameters that will be fed to the CLI.

TABLE_HEADERS: ClassVar[tuple[_ColumnSpec, ...]] = (ColumnSpec(id='id', label='ID', description='Fully-qualified parameter path (`cli.subcommand.param-name`) derived from the [`click.Command`](https://click.palletsprojects.com/en/stable/api/#click.Command) tree. Doubles as the key used to address the parameter from a configuration file.'), ColumnSpec(id='spec', label='Spec.', description='Option/argument specification string (like `-v, --verbose`) extracted from [`click.Parameter.get_help_record()`](https://click.palletsprojects.com/en/stable/api/#click.Parameter).'), ColumnSpec(id='class', label='Class', description="Fully-qualified class of the parameter: a subclass of [`click.Option`](https://click.palletsprojects.com/en/stable/api/#click.Option), [`click.Argument`](https://click.palletsprojects.com/en/stable/api/#click.Argument), [`cloup.Option`](https://cloup.readthedocs.io/en/stable/autoapi/cloup/index.html#cloup.Option), or one of Click Extra's own wrappers ([`click_extra.parameters.Option`](#click_extra.parameters.Option), [`click_extra.parameters.Argument`](#click_extra.parameters.Argument), [`click_extra.parameters.ExtraOption`](#click_extra.parameters.ExtraOption))."), ColumnSpec(id='param_type', label='Param type', description='Click value converter class: a subclass of [`click.ParamType`](https://click.palletsprojects.com/en/stable/api/#click.ParamType) like [`click.IntRange`](https://click.palletsprojects.com/en/stable/api/#click.IntRange), [`click.Choice`](https://click.palletsprojects.com/en/stable/api/#click.Choice), or a Click Extra type.'), ColumnSpec(id='python_type', label='Python type', description='Python built-in type the parsed value resolves to: [`str`](https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str), [`int`](https://docs.python.org/3/library/functions.html#int), [`float`](https://docs.python.org/3/library/functions.html#float), [`bool`](https://docs.python.org/3/library/functions.html#bool), or [`list`](https://docs.python.org/3/library/stdtypes.html#list). Computed by [`ParamStructure.get_param_type()`](#click_extra.parameters.ParamStructure.get_param_type) from the Click `Param type`.'), ColumnSpec(id='hidden', label='Hidden', description="Reflects [`click.Option`'s `hidden`](https://click.palletsprojects.com/en/stable/api/#click.Option) constructor argument: the option is omitted from `--help` output. Empty for [`click.Argument`](https://click.palletsprojects.com/en/stable/api/#click.Argument), which does not support hiding."), ColumnSpec(id='exposed', label='Exposed', description="Reflects [`click.Parameter`'s `expose_value`](https://click.palletsprojects.com/en/stable/api/#click.Parameter) constructor argument: whether the parsed value is forwarded to the command callback. Eager options like `--show-params` and `--help` typically run a callback and exit, so they are not exposed."), ColumnSpec(id='allowed_in_conf', label='Allowed in conf?', description='Click Extra-specific: whether the parameter is reachable from a configuration file. Controlled by [`ParamStructure.excluded_params`](#click_extra.parameters.ParamStructure.excluded_params) and [`included_params`](#click_extra.parameters.ParamStructure.included_params). Empty when the CLI has no [`--config` option](config.md).'), ColumnSpec(id='envvars', label='Env. vars.', description="Environment variables read for this parameter: the explicit [`click.Parameter`'s `envvar`](https://click.palletsprojects.com/en/stable/api/#click.Parameter) plus the auto-resolved IDs documented in [Environment variables](envvar.md)."), ColumnSpec(id='default', label='Default', description='Default value returned by [`click.Parameter.get_default()`](https://click.palletsprojects.com/en/stable/api/#click.Parameter.get_default), rendered as its Python `repr()`.'), ColumnSpec(id='is_flag', label='Is flag', description="Reflects [`click.Option`'s `is_flag`](https://click.palletsprojects.com/en/stable/api/#click.Option): whether the option behaves as a flag (no value taken from the command line). Empty for [`click.Argument`](https://click.palletsprojects.com/en/stable/api/#click.Argument)."), ColumnSpec(id='flag_value', label='Flag value', description="Reflects [`click.Option`'s `flag_value`](https://click.palletsprojects.com/en/stable/api/#click.Option): the Python value substituted for the option when its flag is used. Defaults to `True` for boolean flags, can be any value for flag-value style options (like `@option('--upper', 'transform', flag_value='upper')`)."), ColumnSpec(id='is_bool_flag', label='Is bool flag', description='Reflects `click.Option.is_bool_flag` (set internally by Click when `flag_value` is `True` or `False`): the option is a *true* boolean flag, as opposed to a flag-value style option.'), ColumnSpec(id='multiple', label='Multiple', description="Reflects [`click.Parameter`'s `multiple`](https://click.palletsprojects.com/en/stable/api/#click.Parameter): the parameter can be repeated on the command line, collecting values into a tuple."), ColumnSpec(id='nargs', label='Nargs', description="Reflects [`click.Parameter`'s `nargs`](https://click.palletsprojects.com/en/stable/api/#click.Parameter): the number of CLI tokens the parameter consumes. `1` is the default; `-1` denotes a variadic argument."), ColumnSpec(id='prompt', label='Prompt', description="Reflects [`click.Option`'s `prompt`](https://click.palletsprojects.com/en/stable/api/#click.Option): the text shown to the user when the option is not provided on the command line. Empty when no prompt is configured."), ColumnSpec(id='confirmation_prompt', label='Confirmation prompt', description="Reflects [`click.Option`'s `confirmation_prompt`](https://click.palletsprojects.com/en/stable/api/#click.Option): whether the user is asked to enter the value twice for confirmation."), ColumnSpec(id='value', label='Value', description='Current value of the parameter at invocation time, computed by [`click.Parameter.consume_value()`](https://click.palletsprojects.com/en/stable/api/#click.Parameter) from the merged sources (CLI, environment, config file, default).'), ColumnSpec(id='source', label='Source', description='Provenance of the resolved value: a [`click.core.ParameterSource`](https://click.palletsprojects.com/en/stable/api/#click.core.ParameterSource) enum member such as `COMMANDLINE`, `ENVIRONMENT`, `DEFAULT_MAP`, or `DEFAULT`.'))

Rich column registry for the --show-params table.

Each entry is a click_extra.table.ColumnSpec carrying the column’s stable id (used by --columns and as structured-format key), its display label, and a MyST/Markdown description consumed by the documentation’s auto-generated Available columns section. Iteration yields columns in canonical display order.

classmethod column_labels()[source]

Return just the display labels of TABLE_HEADERS (in order).

Return type:

tuple[str, ...]

classmethod column_ids()[source]

Return just the stable IDs of TABLE_HEADERS (in order).

Return type:

tuple[str, ...]

classmethod find_column(column_id)[source]

Return the ColumnSpec matching column_id.

Raises KeyError if no column has this ID; callers should convert the error into a click.UsageError when surfaced to a user.

classmethod render_doc_table()[source]

Render TABLE_HEADERS as a Markdown table for documentation.

Used by the show_params_columns_table MyST substitution in docs/conf.py to feed the Available columns section of docs/parameters.md: editing a description here automatically rebuilds the docs table on the next sphinx-build.

Return type:

str

excluded_params

Deactivates the blocking of any parameter.

included_params

No allowlist filter; show all parameters.

print_params(ctx, param, value)[source]

Introspect the current CLI and print its parameter metadata table.

Thin wrapper over render_params_table(), the shared rendering core also driving click-extra wrap --show-params for foreign CLIs. The live invocation context carries everything the core needs: the captured RAW_ARGS (attached by Command/Group) for value and source resolution, plus any sibling --table-format / --columns options.

Return type:

None

exception click_extra.SkippedTest[source]

Bases: Exception

Raised when a test case should be skipped.

class click_extra.SortByOption(*header_defs, param_decls=None, default=None, expose_value=False, cell_key=None, help='Sort table by this column. Repeat to set priority.', **kwargs)[source]

Bases: ExtraOption

A --sort-by option whose choices are derived from column definitions.

Stores the selected column IDs in ctx.meta[click_extra.context.SORT_BY] and bakes a row sort into ctx.print_table so that table output is automatically sorted, without changing its (table_data, headers) call contract. The option accepts multiple=True, so users can repeat --sort-by to define a multi-column sort priority.

@command
@table_format_option
@sort_by_option(
    ("Package ID", "package_id"),
    ("Name", "package_name"),
    ("Manager", "manager_id"),
    ("Version", None),
)
@pass_context
def my_cmd(ctx):
    ctx.print_table(rows, headers)
init_sort(ctx, param, sort_columns)[source]

Bake the row sort key into ctx.print_table.

Builds the sort key from this option’s column definitions and the selected sort_columns, then rebinds ctx.print_table to print_table() with that key applied. The call contract is the same sorted or not: ctx.print_table(table_data, headers).

Return type:

None

class click_extra.Spinner(label='', *, frames=None, spinner=None, reverse=False, interval=None, delay=0.0, style=None, timer=False, stream=None, enabled=None, hide_cursor=True, beep=False)[source]

Bases: object

A thread-animated, indeterminate progress spinner usable as a context manager.

The animation runs on a background daemon thread, leaving the calling thread free to block on the actual work. Entering the context (or calling start()) begins the animation; leaving it (or calling stop()) halts the thread and erases the spinner line so it never lingers above the next output.

Note

A single Spinner instance drives one animation at a time. mpm and similar tools run their subprocesses sequentially, so one shared instance whose label is reassigned between steps is enough; for concurrent work, use one instance per thread.

Configure (but do not start) the spinner.

Parameters:
  • label (str | Callable[..., Any]) – text shown after the spinner glyph. As a special case, a bare @Spinner decorator passes the wrapped function here instead; it is detected and the label defaults to empty.

  • frames (Sequence[str] | None) – the animation frames, cycled in order. Defaults to SPINNER_FRAMES, or the spinner preset’s frames when given.

  • spinner (SpinnerPreset | None) – a SpinnerPreset from the SPINNERS catalog (spinner=SPINNERS["moon"]), supplying both frames and a tuned interval. An explicit frames or interval still overrides it.

  • reverse (bool) – cycle the frames backwards, spinning the animation the other way. Set it when the rotation runs counter to what you expect; it composes with any custom frames.

  • interval (float | None) – seconds between two frames. Defaults to 0.1, or the spinner preset’s interval when given.

  • delay (float) – seconds to wait before drawing the first frame. A non-zero delay keeps the spinner silent for calls that finish quickly, so it only surfaces once an operation is genuinely slow.

  • style (Style | None) – a Style applied to the spinner glyph, label and timer (Style(fg="cyan", bold=True)). Color is decoupled from animation: --no-color / NO_COLOR strip it while the spinner keeps spinning (see ProgressOption).

  • timer (bool | Callable[[float], str]) – append the elapsed wall-clock time to the spinner, and to any final ok() / fail() line. True uses the default compact format (2.3s, 1:05, then 1:02:03). Pass a callable (seconds: float) -> str to format the duration yourself, like timer=lambda s: f"{s / 60:.0f}m" for whole minutes.

  • stream (IO[str] | None) – where to draw; defaults to sys.stderr so the spinner never mixes into stdout data.

  • enabled (bool | None) – force the spinner on or off. None (the default) auto-detects, animating only when stream is a TTY.

  • hide_cursor (bool) – hide the text cursor while spinning and restore it on stop.

  • beep (bool) – ring the terminal bell once when the spinner stops. It fires only when the spinner was active, so a disabled or redirected spinner stays silent.

Raises:

ValueError – if style carries a color or attribute that cannot be rendered.

label: str

Text drawn after the spinner glyph.

Reassign it at any time while the spinner runs to reflect the current step; the animation thread reads it afresh on every frame.

property elapsed_time: float

Seconds elapsed since start(), frozen once stop() is called.

Returns 0.0 before the spinner has started.

property shown: bool

Whether the spinner has drawn at least one frame to its stream.

True only once an animation frame was actually rendered. It stays False for a disabled spinner (off a TTY, on a TERM=dumb terminal, or with enabled=False) and for a call that finishes within delay, before the first frame. Reset by start().

Use it to gate output that should mirror the spinner’s visibility. ok() and fail() write their line unconditionally, so an outcome is still recorded in a pipe or log; guard them with shown when you only want the finisher on screen after a spinner the user actually saw:

with Spinner("Baking bread") as spinner:
    bake()
    if spinner.shown:
        spinner.ok()
start()[source]

Begin animating on a background thread, unless the spinner is disabled.

A disabled spinner (non-TTY stream, or enabled=False) returns at once without spawning a thread or emitting anything (but still records the start time, so a later ok() / fail() can report a duration).

Return type:

None

stop()[source]

Halt the animation and erase the spinner line.

Idempotent and safe to call when the spinner never started. Restores the cursor and clears the line only if the animation actually drew to the terminal.

Return type:

None

echo(message='')[source]

Print message on its own line above the running spinner.

Click’s click.progressbar() and a bare print both fight the animation: a frame drawn between the cursor returns and the text mangles the line. echo() takes the same draw lock as the animation thread, erases the in-progress frame, writes message followed by a newline, and lets the next tick redraw the spinner underneath. It is safe to call from another thread while the spinner runs.

Output goes to the spinner’s own stream (stderr by default), so results written to stdout never need it. When the spinner is not animating (disabled, or a non-TTY stream), it degrades to a plain write of message with no control codes.

Return type:

None

ok(symbol=None, *, style=None)[source]

Stop the spinner and leave a persistent success line on screen.

Where stop() erases the spinner, ok() replaces the final frame with symbol followed by the current label (and the elapsed time when timer is set), then keeps that line. symbol defaults to the themed success glyph OK_GLYPH (), painted with the active theme’s success slot unless style overrides it. Color is stripped under --no-color / NO_COLOR; the glyph stays.

Return type:

None

fail(symbol=None, *, style=None)[source]

Stop the spinner and leave a persistent failure line on screen.

The failure counterpart of ok(), defaulting to KO_GLYPH () painted with the active theme’s error slot.

Return type:

None

class click_extra.SpinnerPreset(frames: tuple[str, ...], interval: float)[source]

Bases: NamedTuple

A named spinner animation: its frames and the interval they look best at.

The SPINNERS catalog is ported from cli-spinners, with intervals converted from milliseconds to seconds. Pass one to Spinner via its spinner argument.

Create new instance of SpinnerPreset(frames, interval)

frames: tuple[str, ...]

The animation frames, cycled in order.

interval: float

Seconds between two frames, tuned per spinner upstream.

class click_extra.StreamHandler(stream=None)[source]

Bases: StreamHandler

A handler to output logs to the console.

Wraps logging.StreamHandler, but use click.echo() to support color printing.

Only <stderr> or <stdout> are allowed as output stream.

If stream is not specified, <stderr> is used by default

Initialize the handler.

If stream is not specified, sys.stderr is used.

property stream: IO[Any]

The stream to which logs are written.

A proxy of the parent logging.StreamHandler’s stream attribute.

Redefined here to enforce checks on the stream value.

emit(record)[source]

Use click.echo() to print to the console.

Return type:

None

class click_extra.Style(fg=None, bg=None, bold=None, dim=None, underline=None, overline=None, italic=None, blink=None, reverse=None, strikethrough=None, text_transform=None)[source]

Bases: Style

cloup.Style with extra ergonomics.

See the module docstring for the full list of additions. The runtime contract (calling the instance to apply styling, equality, hashing, with_()) is otherwise identical to cloup.Style.

fg: str | tuple[int, int, int] | int | None = None

Foreground color: named ANSI string, #rrggbb hex, RGB tuple, or palette index.

bg: str | tuple[int, int, int] | int | None = None

Background color: named ANSI string, #rrggbb hex, RGB tuple, or palette index.

cascade(base)[source]

Return a copy with None fields filled in from base.

The instance’s own non-None values always win: cascade only fills gaps. Useful for theme inheritance: derived.cascade(parent) keeps derived’s overrides and inherits the rest from parent.

Return type:

Style

to_dict()[source]

Serialize to a plain dict with only the set fields.

RGB tuples are emitted as #rrggbb strings so the result round-trips through TOML/JSON/YAML untouched. Pair with from_dict() to rebuild a Style.

Return type:

dict[str, Any]

classmethod from_dict(data)[source]

Build a Style from the plain dict produced by to_dict().

Validates that every key in data names a known Style field and raises TypeError otherwise. Pair with to_dict() to round-trip through TOML/JSON/YAML.

Return type:

Style

to_css()[source]

Render the style as a semicolon-separated CSS declaration list.

Style(fg="#f1fa8c", bold=True).to_css() returns "color: #f1fa8c; font-weight: bold". Suitable for inline style="..." attributes on HTML spans.

Return type:

str

classmethod from_ansi(escape)[source]

Parse one or more consecutive ANSI SGR escapes into a Style.

Supports the standard 8/16-color codes (30–37, 40–47, 90–97, 100–107), the 38;5;n / 48;5;n 256-color extension, and the 38;2;r;g;b / 48;2;r;g;b 24-bit extension. Reset codes (0) are ignored. Multiple back-to-back escapes (as click emits when combining colors with attributes: \x1b[31m\x1b[1m) are merged into a single Style.

Return type:

Style

contrast_ratio(other)[source]

Return the WCAG 2.x contrast ratio between this fg and other’s fg.

Result is in [1, 21]: 1 = identical colors (no contrast), 21 = maximum contrast (black on white). WCAG AA requires 4.5+ for normal text, 3.0+ for large text; AAA wants 7.0+ and 4.5+ respectively.

Return type:

float

class click_extra.TableFormat(*values)[source]

Bases: Enum

Enumeration of supported table formats.

Hard-coded to be in alphabetical order. Content of this enum is checked in unit tests.

Warning

The youtrack format is missing in action from any official JetBrains documentation. It will be removed in python-tabulate v0.11.

ALIGNED = 'aligned'
ASCIIDOC = 'asciidoc'
COLON_GRID = 'colon-grid'
CSV = 'csv'
CSV_EXCEL = 'csv-excel'
CSV_EXCEL_TAB = 'csv-excel-tab'
CSV_UNIX = 'csv-unix'
DOUBLE_GRID = 'double-grid'
DOUBLE_OUTLINE = 'double-outline'
FANCY_GRID = 'fancy-grid'
FANCY_OUTLINE = 'fancy-outline'
GITHUB = 'github'
GRID = 'grid'
HEAVY_GRID = 'heavy-grid'
HEAVY_OUTLINE = 'heavy-outline'
HJSON = 'hjson'
HTML = 'html'
JIRA = 'jira'
JSON = 'json'
JSON5 = 'json5'
JSONC = 'jsonc'
LATEX = 'latex'
LATEX_BOOKTABS = 'latex-booktabs'
LATEX_LONGTABLE = 'latex-longtable'
LATEX_RAW = 'latex-raw'
MEDIAWIKI = 'mediawiki'
MIXED_GRID = 'mixed-grid'
MIXED_OUTLINE = 'mixed-outline'
MOINMOIN = 'moinmoin'
ORGTBL = 'orgtbl'
OUTLINE = 'outline'
PIPE = 'pipe'
PLAIN = 'plain'
PRESTO = 'presto'
PRETTY = 'pretty'
PSQL = 'psql'
ROUNDED_GRID = 'rounded-grid'
ROUNDED_OUTLINE = 'rounded-outline'
RST = 'rst'
SIMPLE = 'simple'
SIMPLE_GRID = 'simple-grid'
SIMPLE_OUTLINE = 'simple-outline'
TEXTILE = 'textile'
TOML = 'toml'
TSV = 'tsv'
UNSAFEHTML = 'unsafehtml'
VERTICAL = 'vertical'
XML = 'xml'
YAML = 'yaml'
YOUTRACK = 'youtrack'
property is_markup: bool

Whether this format is a markup rendering.

Markup formats have ANSI color codes stripped from their output by default. Use the --color flag to preserve them.

class click_extra.TableFormatOption(param_decls=None, type=EnumChoice('aligned', 'asciidoc', 'colon-grid', 'csv', 'csv-excel', 'csv-excel-tab', 'csv-unix', 'double-grid', 'double-outline', 'fancy-grid', 'fancy-outline', 'github', 'grid', 'heavy-grid', 'heavy-outline', 'hjson', 'html', 'jira', 'json', 'json5', 'jsonc', 'latex', 'latex-booktabs', 'latex-longtable', 'latex-raw', 'mediawiki', 'mixed-grid', 'mixed-outline', 'moinmoin', 'orgtbl', 'outline', 'pipe', 'plain', 'presto', 'pretty', 'psql', 'rounded-grid', 'rounded-outline', 'rst', 'simple', 'simple-grid', 'simple-outline', 'textile', 'toml', 'tsv', 'unsafehtml', 'vertical', 'xml', 'yaml', 'youtrack'), default=TableFormat.ROUNDED_OUTLINE, expose_value=False, is_eager=True, help='Rendering style of tables.', **kwargs)[source]

Bases: ExtraOption

A pre-configured option that is adding a --table-format flag to select the rendering style of a table.

The selected table format ID is made available in the context in ctx.meta[click_extra.context.TABLE_FORMAT], and two helper methods are added to the context:

  • ctx.render_table(table_data, headers, **kwargs): renders and returns the table as a string,

  • ctx.print_table(table_data, headers, **kwargs): renders and prints the table to the console.

Where:

  • table_data is a 2-dimensional iterable of iterables for rows and cells values,

  • headers is a list of string to be used as column headers,

  • **kwargs are any extra keyword arguments supported by the underlying table formatting function.

init_formatter(ctx, param, table_format)[source]

Save in the context: table_format, render_table & print_table.

Return type:

None

class click_extra.TelemetryOption(param_decls=None, default=False, expose_value=False, envvar=None, show_envvar=True, help='Collect telemetry and usage data.', **kwargs)[source]

Bases: ExtraOption

A pre-configured --telemetry/--no-telemetry option flag.

Respects the proposed DO_NOT_TRACK environment variable as a unified standard to opt-out of telemetry for TUI/console apps.

The DO_NOT_TRACK convention takes precedence over the user-defined environment variables and the auto-generated values.

The resolved value is stored in ctx.meta[click_extra.context.TELEMETRY], aligning with every other Click Extra option’s per-invocation context-meta storage pattern.

set_telemetry(ctx, param, value)[source]

Store the resolved telemetry opt-in flag on the context’s meta dict.

Reads via click_extra.context.get(ctx, click_extra.context.TELEMETRY). Renamed from save_telemetry to align with the set_<key> convention used by every other ctx.meta-writing callback.

Return type:

None

class click_extra.TestPlanConfig(file='./tests/cli-test-plan.yaml', inline=None, timeout=None)[source]

Bases: object

Config schema for a project’s test plan, read from [tool.<cli>.test-plan].

The test-plan CLI command resolves its cases from this config when no plan is given on the command line. Map it onto an app’s config section with a field carrying metadata={"click_extra.config_path": "test-plan"}.

file: str = './tests/cli-test-plan.yaml'

Path to a YAML test plan file, resolved relative to the project root.

inline: str | None = None

Inline YAML test plan, an alternative to file. Takes precedence.

timeout: int | None = None

Default timeout (seconds) for each case that does not set its own.

None leaves cases unbounded unless --timeout is passed.

class click_extra.ThemeOption(param_decls=None, default='dark', is_eager=True, expose_value=False, help='Color theme used for help screens.', **kwargs)[source]

Bases: ExtraOption

A pre-configured option that adds --theme to select the help-screen palette.

Accepts any name registered in theme_registry or in the per-invocation overrides loaded by ConfigOption from [tool.<cli>.themes.<name>]. Validation goes through ThemeChoice, which reads the live registry at parse time, so config-defined themes appear as valid choices and in the --help metavar without any further wiring.

The resolved HelpTheme lands on the Click context under click_extra.context.THEME and applies for the duration of the current invocation only.

set_theme(ctx, param, value)[source]

Resolve the chosen theme name and store it on the Click context.

ThemeChoice has already validated value against the live registry by the time this fires, so the lookup is unconditional.

Return type:

None

class click_extra.TimerOption(param_decls=None, default=False, expose_value=False, is_eager=True, help='Measure and print elapsed execution time.', **kwargs)[source]

Bases: ExtraOption

A pre-configured option that is adding a --time/--no-time flag to print elapsed time at the end of CLI execution.

The start time is made available in the context in ctx.meta[click_extra.context.START_TIME].

print_timer()[source]

Compute and print elapsed execution time.

Always prints, even when a sibling eager option (--version, --show-params, --show-config…) short-circuited the command body via ctx.exit(). That makes --time a usable probe for the cost of Click Extra’s own machinery (option parsing, config loading, eager callbacks), not just user command bodies.

Return type:

None

init_timer(ctx, param, value)[source]

Set up the execution-timer machinery for the current invocation.

Captures time.perf_counter() as the start time, stores it on ctx.meta under click_extra.context.START_TIME, and queues print_timer() as a context-close callback so the elapsed duration is printed even when a sibling eager option (--version, --show-params…) short-circuits the command body.

Renamed from register_timer_on_close to align with the init_<system> convention shared with init_formatter and init_sort.

Return type:

None

class click_extra.Tuple(types)[source]

Bases: CompositeParamType[tuple[Any, …]]

The default behavior of Click is to apply a type on a value directly. This works well in most cases, except for when nargs is set to a fixed count and different types should be used for different items. In this case the Tuple type can be used. This type can only be used if nargs is set to a fixed number.

For more information see Multi Value Options as Tuples.

This can be selected by using a Python tuple literal as a type.

Parameters:

types (Sequence[type[Any] | ParamType[Any]]) – a list of types that should be used for the tuple items.

types: Sequence[ParamType[Any]]
to_info_dict()[source]

Gather information that could be useful for a tool generating user-facing documentation.

Use click.Context.to_info_dict() to traverse the entire CLI structure.

Added in version 8.0.

Return type:

TupleInfoDict

property name: str
property arity: int

int([x]) -> integer int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating-point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by ‘+’ or ‘-’ and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer iteral. >>> int(‘0b100’, base=0) 4

convert(value, param, ctx)[source]

Convert the value to the correct type. This is not called if the value is None (the missing value).

This must accept string values from the command line, as well as values that are already the correct type. It may also convert other compatible types.

The param and ctx arguments may be None in certain situations, such as when converting prompt input.

If the value cannot be converted, call fail() with a descriptive message.

Parameters:
  • value (t.Any) – The value to convert.

  • param (Parameter | None) – The parameter that is using this type to convert its value. May be None.

  • ctx (Context | None) – The current context that arrived at this value. May be None.

Return type:

tuple[t.Any, …]

exception click_extra.UsageError(message, ctx=None)[source]

Bases: ClickException

An internal exception that signals a usage error. This typically aborts any further handling.

Parameters:
  • message (str) – the error message to display.

  • ctx (Context | None) – optionally the context that caused this error. Click will fill in the context automatically in some situations.

exit_code = 2

The exit code for this exception.

cmd: Command | None
show(file=None)[source]
Return type:

None

class click_extra.ValidateConfigOption(param_decls=None, type=<click.types.Path object>, is_eager=True, expose_value=False, help='Validate the configuration file and exit.', **kwargs)[source]

Bases: ExtraOption

A pre-configured option adding --validate-config CONFIG_PATH.

Loads the config file at the given path, validates it against the CLI’s parameter structure in strict mode, reports results, and exits.

validate_config(ctx, param, value)[source]

Load, parse, and validate the configuration file, then exit.

Validation runs three checks in order, every one of them under the same ValidationError shape so the reported path is always rooted at the configuration file:

  1. CLI-parameter strict check on the non-opaque part of the document.

  2. Schema processing, if a config_schema is configured: catches type errors and unknown keys inside the dataclass-described section.

  3. Each registered ConfigValidator runs against its declared opaque sub-tree.

Every detected error is emitted before exiting, so a single --validate-config run surfaces the full list of fixes the user needs to apply.

Return type:

None

exception click_extra.ValidationError(path, message, code=None)[source]

Bases: Exception

Raised when a configuration file fails validation.

A single, structured exception type that uniformly carries the dotted path of the offending key, a human-readable message, and an optional code for programmatic handling. Used by click-extra’s built-in strict-mode check and by every user-registered ConfigValidator, so downstream apps and --validate-config see the same error shape regardless of who detected the problem.

Parameters:
  • path (str) – Dotted path to the offending key, relative to the configuration file root (like "my-cli.managers.winget.cli_searchpath"). An empty string means the error applies to the document as a whole.

  • message (str) – Human-readable description of the failure. Should be a single sentence, no trailing punctuation, no path repeated.

  • code (str | None) – Optional machine-readable error code (like "unknown_field") for callers that want to dispatch on error type without parsing the message string.

class click_extra.ValidationReport(schema_instance, opaque_subtrees, errors, merged_conf=None)[source]

Bases: object

Outcome of one pass through run_config_validation().

Bundles everything a caller needs after validating a parsed configuration document: the typed schema instance, the extracted opaque sub-trees, the template-filtered config ready for default_map, and every error detected across all validation stages.

Note

The report holds references to the parsed sub-trees, not copies, so building it is cheap regardless of document size.

schema_instance: Any | None

Typed object produced by the configured schema callable.

None when no schema is configured, or when the schema stage raised (in which case the failure is recorded in errors).

opaque_subtrees: dict[str, dict[str, Any]]

Extracted extension sub-trees, keyed by dotted path relative to the app section. Only paths actually present in the document appear here, so callers can re-route them to per-path validators or stash them on ctx.meta.

errors: tuple[ValidationError, ...]

Every ValidationError detected, in stage order (unknown CLI-flag keys first, then schema errors, then validator failures). Empty on success.

With collect_all=False this holds at most one error: the first failure short-circuits the remaining stages.

merged_conf: dict[str, Any] | None = None

The CLI-flag-bound configuration merged onto params_template: the payload _install_default_map() layers into the context’s default_map.

None when params_template was None (no strict check) or the strict check raised. Read it only on a successful report: it is the same value merge_default_map() would recompute, so reusing it avoids a second normalize/strip/merge pass.

property ok: bool

True when no error was detected.

class click_extra.VerboseOption(param_decls=None, count=True, **kwargs)[source]

Bases: _VerbosityOption

--verbose/-v option to raise the log level of _VerbosityOption by one step per repetition.

Each -v raises the verbosity by one LogLevel step. The option can be repeated, so -vv (or -v -v) raises it by two steps.

The base level the counter starts from is sourced from VerbosityOption.default. So with --verbosity’s default left at WARNING:

  • -v raises the level to INFO,

  • -vv raises the level to DEBUG,

  • any further repetition is clamped at the loudest level, so -vvvvv for example resolves to DEBUG.

-v shares a single signed counter with QuietOption’s -q, so the two cancel out: -v -q leaves the level unchanged. See _VerbosityOption.resolve_level for the full reconciliation rule with --verbosity.

Set up a verbosity-altering option.

Parameters:

default_logger – If a logging.Logger object is provided, that’s the instance to which we will set the level to. If the parameter is a string and is found in the global registry, we will use it as the logger’s ID. Otherwise, we will create a new logger with new_logger() Default to the global root logger.

set_level(ctx, param, value)[source]

Record the -v repetition count, then reconcile.

The number of repetitions is saved in ctx.meta[click_extra.context.VERBOSE] and folded into the verbosity counter by _VerbosityOption.resolve_level.

Return type:

None

class click_extra.VerbosityOption(param_decls=None, default_logger='root', default=LogLevel.WARNING, metavar='LEVEL', type=EnumChoice('CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG'), help='Either CRITICAL, ERROR, WARNING, INFO, DEBUG.', **kwargs)[source]

Bases: _VerbosityOption

--verbosity LEVEL option to set the log level of _VerbosityOption.

Set up a verbosity-altering option.

Parameters:

default_logger (Logger | str) – If a logging.Logger object is provided, that’s the instance to which we will set the level to. If the parameter is a string and is found in the global registry, we will use it as the logger’s ID. Otherwise, we will create a new logger with new_logger() Default to the global root logger.

set_level(ctx, param, value)[source]

Record the --verbosity value, then reconcile.

The value passed to --verbosity is saved in ctx.meta[click_extra.context.VERBOSITY].

Return type:

None

class click_extra.VersionOption(param_decls=None, message=None, fields=None, styles=None, message_style=None, is_flag=True, expose_value=False, is_eager=True, help='Show the version and exit.', **kwargs)[source]

Bases: ExtraOption

Gather CLI metadata and prints a colored version string.

Note

This started as a copy of the standard @click.version_option() decorator, but is no longer a drop-in replacement. Hence the Extra prefix.

This address the following Click issues:

  • click#2324, to allow its use with the declarative params= argument.

  • click#2331, by distinguishing the module from the package.

  • click#1756, by allowing path and Python version.

Preconfigured as a --version option flag.

Parameters:
  • message (str | None) – the message template to print, in format string syntax. Defaults to {prog_name}, version {version}.

  • fields (Mapping[str, Any] | None) – mapping of template field name to a forced value, overriding the value auto-computed for that field. Keys must be members of template_fields (for example {"version": "1.2.3"}).

  • styles (Mapping[str, Callable[[str], str] | None] | None) – mapping of template field name to its Style, merged over default_styles. Pass None as a value to clear a field’s default style. Keys must be members of template_fields.

  • message_style (Callable[[str], str] | None) – fallback style for the message literals and for any field that has no style of its own.

template_fields: tuple[str, ...] = ('module', 'module_name', 'module_file', 'module_version', 'package_name', 'package_version', 'author', 'license', 'exec_name', 'version', 'git_repo_path', 'git_branch', 'git_long_hash', 'git_short_hash', 'git_date', 'git_tag', 'git_tag_sha', 'git_distance', 'git_dirty', 'prog_name', 'env_info')

List of field IDs recognized by the message template.

default_styles: ClassVar[dict[str, Callable[[str], str]]] = {'env_info': Style(fg='bright_black'), 'exec_name': Style(fg='bright_white', bold), 'git_branch': Style(fg='cyan'), 'git_date': Style(fg='bright_black'), 'git_dirty': Style(fg='red'), 'git_distance': Style(fg='green'), 'git_long_hash': Style(fg='yellow'), 'git_repo_path': Style(fg='bright_black'), 'git_short_hash': Style(fg='yellow'), 'git_tag': Style(fg='cyan'), 'git_tag_sha': Style(fg='yellow'), 'module_name': Style(fg='bright_white', bold), 'module_version': Style(fg='green'), 'package_name': Style(fg='bright_white', bold), 'package_version': Style(fg='green'), 'prog_name': Style(fg='bright_white', bold), 'version': Style(fg='green')}

Default style for each template field.

Fields absent from this mapping render with no style of their own and fall back to message_style (or no color when that is unset). User-provided styles are merged over these defaults.

message: str = '{prog_name}, version {version}'

Default message template used to render the version string.

static cli_frame()[source]

Returns the frame in which the CLI is implemented.

Inspects the execution stack frames to find the package in which the user’s CLI is implemented.

Returns the frame itself.

Return type:

FrameType

property module: ModuleType[source]

Returns the module in which the CLI resides.

property module_name: str[source]

Returns the full module name or __main__.

property module_file: str | None[source]

Returns the module’s file full path.

property module_version: str | None[source]

Returns the string found in the local __version__ variable.

Hint

__version__ is an old pattern from early Python packaging. It is not a standard variable and is not defined in the packaging PEPs.

You should prefer using the package_version property below instead, which uses the standard library importlib.metadata API.

We’re still supporting it for backward compatibility with existing codebases, as Click removed it in version 8.2.0.

property package_name: str | None[source]

Returns the package name.

property package_version: str | None[source]

Returns the package version if installed.

Resolved from the distribution name (see _distribution_name) via importlib.metadata.version(). Returns None if the package is not installed or cannot be resolved.

property author: str | None[source]

Returns the package author(s) from its core metadata.

Delegates to resolve_author(): prefers the Author field, then the Maintainer field, then the display name parsed out of the Author-email / Maintainer-email fields (Name <email>). Returns None if no author can be determined.

property license: str | None[source]

Returns the package license from its core metadata.

Delegates to resolve_license(): prefers the SPDX License-Expression field, falls back to the human-readable name of the first License :: trove classifier, then to the free-form License field. Returns None if no license can be determined.

property exec_name: str[source]

User-friendly name of the executed CLI.

Returns the module name. But if the later is __main__, returns the package name.

If not packaged, the CLI is assumed to be a simple standalone script, and the returned name is the script’s file name (including its extension).

property version: str | None[source]

Return the version of the CLI.

Returns the module version if a __version__ variable is set alongside the CLI in its module.

Else returns the package version if the CLI is implemented in a package, using importlib.metadata.version().

For development versions (containing .dev), automatically appends the Git short hash as a PEP 440 local version identifier, producing versions like 1.2.3.dev0+abc1234. This helps identify the exact commit a dev build was produced from. If Git is unavailable, the plain dev version is returned.

Versions that already contain a + (a pre-baked local version identifier, typically set at build time by CI pipelines) are returned as-is to avoid producing invalid double-suffixed versions like 1.2.3.dev0+abc1234+xyz5678.

property git_repo_path: Path | None[source]

Find the Git repository root directory.

property git_branch: str | None[source]

Returns the current Git branch name.

Checks for a pre-baked __git_branch__ dunder first, then git rev-parse --abbrev-ref HEAD, then .git_archival.json.

property git_long_hash: str | None[source]

Returns the full Git commit hash.

Checks for a pre-baked __git_long_hash__ dunder first, then git rev-parse HEAD, then .git_archival.json.

property git_short_hash: str | None[source]

Returns the short Git commit hash.

Checks for a pre-baked __git_short_hash__ dunder first, then git rev-parse --short HEAD, then .git_archival.json (where it is derived from the first 7 characters of the full hash).

Hint

The short hash is usually the first 7 characters of the full hash, but this is not guaranteed to be the case.

But it is at least guaranteed to be unique within the repository, and a minimum of 4 characters.

property git_date: str | None[source]

Returns the commit date in ISO format: YYYY-MM-DD HH:MM:SS +ZZZZ.

Checks for a pre-baked __git_date__ dunder first, then git show -s --format=%ci HEAD, then .git_archival.json (whose node-date is strict ISO 8601, like 2021-01-01T12:00:00+00:00).

property git_tag: str | None[source]

Returns the Git tag pointing at HEAD, if any.

Checks for a pre-baked __git_tag__ dunder first, then git describe --tags --exact-match HEAD, then .git_archival.json.

Returns None if HEAD is not at a tagged commit.

property git_tag_sha: str | None[source]

Returns the commit SHA that the current tag points at.

Checks for a pre-baked __git_tag_sha__ dunder first, then git rev-list -1 on the tag returned by git_tag, then .git_archival.json. Returns None if HEAD is not at a tag.

property git_distance: str | None[source]

Number of commits since the most recent tag, or None.

Checks for a pre-baked __git_distance__ dunder first, then parses git describe --tags --long, then falls back to .git_archival.json. None when no tag is reachable or Git is unavailable.

property git_dirty: str | None[source]

Work-tree state: "dirty", "clean" or None.

Checks for a pre-baked __git_dirty__ dunder first, then runs git status --porcelain. None when not in a Git repository or Git is unavailable. There is no .git_archival.json fallback: an archive has no work tree, so its state is unknowable.

property prog_name: str | None[source]

Return the name of the CLI, from Click’s point of view.

Get the info_name of the root command.

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

Various environment info.

Returns the data produced by boltons.ecoutils.get_profile().

colored_template(template=None)[source]

Insert ANSI styles to a message template.

Accepts a custom template as parameter, otherwise uses the default message defined on the Option instance.

This step is necessary because we need to linearize the template to apply the ANSI codes on the string segments. This is a consequence of the nature of ANSI, directives which cannot be encapsulated within another (unlike markup tags like HTML).

Return type:

str

render_message(template=None)[source]

Render the version string from the provided template.

Accepts a custom template as parameter, otherwise uses the default self.colored_template() produced by the instance.

Return type:

str

print_debug_message()[source]

Render in debug logs all template fields in color.

Todo

Pretty print JSON output (easier to read in bug reports)?

Return type:

None

print_and_exit(ctx, param, value)[source]

Print the version string and exits.

Also stores all version string elements in the Context’s meta dict.

Return type:

None

class click_extra.ZeroExitOption(param_decls=None, default=False, expose_value=False, is_flag=True, help='Always exit with a status code of 0, even when problems are found.', **kwargs)[source]

Bases: ExtraOption

A pre-configured -0/--zero-exit option flag.

Follows the convention popularized by linters and static analysers, which exit with a non-zero code whenever they report findings so that automation can gate on it. Setting this flag flips that behavior: the CLI returns 0 as long as it ran to completion, reserving non-zero codes for actual execution failures.

The resolved value is stored in ctx.meta[click_extra.context.ZERO_EXIT], aligning with every other Click Extra option’s per-invocation context-meta storage pattern.

Warning

This option is a placeholder: it does not alter the CLI’s exit code by itself. Downstream code must read ctx.meta[click_extra.context.ZERO_EXIT] and act on it.

set_zero_exit(ctx, param, value)[source]

Store the resolved zero-exit flag on the context’s meta dict.

Read via click_extra.context.get(ctx, click_extra.context.ZERO_EXIT).

Return type:

None

click_extra.accessible_option(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.argument(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.basicConfig(*, filename=None, filemode='a', format='{levelname}: {message}', datefmt=None, style='{', level=None, stream=None, handlers=None, force=False, encoding=None, errors='backslashreplace', stream_handler_class=<class 'click_extra.logging.StreamHandler'>, file_handler_class=<class 'logging.FileHandler'>, formatter_class=<class 'click_extra.logging.Formatter'>)[source]

Configure the global root logger.

This function is a wrapper around Python standard library’s logging.basicConfig(), but with additional parameters and tweaked defaults.

It sets up the global root logger, and optionally adds a file or stream handler to it.

Differences in default values:

Argument

basicConfig() default

logging.basicConfig() default

style

{

%

format

{levelname}: {message}

%(levelname)s:%(name)s:%(message)s

This function takes the same parameters as logging.basicConfig(), but require them to be all passed as explicit keywords arguments.

Parameters:
  • filename (str | None) – Specifies that a logging.FileHandler be created, using the specified filename, rather than an StreamHandler.

  • filemode (str) –

    If filename is specified, open the file in this mode.

    Defaults to a.

  • format (str | None) –

    Use the specified format string for the handler.

    Defaults to {levelname}: {message}.

  • datefmt (str | None) – Use the specified date/time format, as accepted by time.strftime().

  • style (Literal['%', '{', '$']) –

    If format is specified, use this style for the format string:

    Defaults to {.

  • level (int | str | None) – Set the root logger level to the specified level.

  • stream (IO[Any] | None) – Use the specified stream to initialize the StreamHandler. Note that this argument is incompatible with filename - if both are present, a ValueError is raised.

  • handlers (Iterable[Handler] | None) – If specified, this should be an iterable of already created handlers to add to the root logger. Any handlers which don’t already have a formatter set will be assigned the default formatter created in this function. Note that this argument is incompatible with filename or stream - if both are present, a ValueError is raised.

  • force (bool) – If this argument is specified as True, any existing handlers attached to the root logger are removed and closed, before carrying out the configuration as specified by the other arguments.

  • encoding (str | None) – Name of the encoding used to decode or encode the file. To be specified along with filename, and passed to logging.FileHandler for opening the output file.

  • errors (str | None) – Optional string that specifies how encoding and decoding errors are to be handled by the logging.FileHandler. Defaults to backslashreplace. Note that if None is specified, it will be passed as such to open().

Return type:

None

Important

Always keep the signature of this function, the default values of its parameters and its documentation in sync with the one from Python’s standard library.

These new arguments are available for better configurability:

Parameters:

Note

I don’t like the camel-cased name of this function and would have called it basic_config(), but it’s kept this way for consistency with Python’s standard library logging.basicConfig().

click_extra.clear()[source]

Drop-in for click.clear() that becomes a no-op under --accessible.

Clearing the screen wipes the scrollback a screen reader relies on and carries no meaning in a linear stream, so accessibility mode skips it entirely. Outside accessibility mode (or with no active context) it defers to click.clear(), which already no-ops when stdout is not a terminal.

Return type:

None

click_extra.color_option(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.columns_option(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.command(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.config_option(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.confirm(text, default=False, abort=False, prompt_suffix=': ', show_default=True, err=False)[source]

Prompts for confirmation (yes/no question).

If the user aborts the input by sending a interrupt signal this function will catch it and raise a Abort exception.

Parameters:
  • text (str) – the question to ask.

  • default (bool | None) – The default value to use when no input is given. If None, repeat until input is given.

  • abort (bool) – if this is set to True a negative answer aborts the exception by raising Abort.

  • prompt_suffix (str) – a suffix that should be added to the prompt.

  • show_default (bool) – shows or hides the default value in the prompt.

  • err (bool) – if set to true the file defaults to stderr instead of stdout, the same as with echo.

Changed in version 8.3.1: A space is no longer appended to the prompt.

Changed in version 8.0: Repeat until input is given if default is None.

Added in version 4.0: Added the err parameter.

Return type:

bool

click_extra.confirmation_option(*param_decls, **kwargs)[source]

Add a --yes option which shows a prompt before continuing if not passed. If the prompt is declined, the program will exit.

Parameters:
  • param_decls (str) – One or more option names. Defaults to the single value "--yes".

  • kwargs (Any) – Extra arguments are passed to option().

Return type:

Callable[[TypeVar(FC, bound= _AnyCallable | Command)], TypeVar(FC, bound= _AnyCallable | Command)]

click_extra.constrained_params(constr, *param_adders)[source]

Return a decorator that adds the given parameters and applies a constraint to them. Equivalent to:

@param_adders[0]
...
@param_adders[-1]
@constraint(constr, <param names>)

This decorator saves you to manually (re)type the parameter names. It can also be used inside @option_group.

Instead of using this decorator, you can also call the constraint itself:

@constr(*param_adders)

but remember that:

  • Python 3.9 is the first that allows arbitrary expressions on the right of @;

  • using a long conditional/composite constraint as decorator may be less readable.

In these cases, you may consider using @constrained_params.

Added in version 0.9.0.

Parameters:
  • constr (Constraint) – an instance of Constraint

  • param_adders (Callable[[Callable[..., Any]], Callable[..., Any]]) – function decorators, each attaching a single parameter to the decorated function.

Return type:

Callable[[TypeVar(F, bound= Callable[..., Any])], TypeVar(F, bound= Callable[..., Any])]

click_extra.constraint(constr, params)[source]

Register a constraint on a list of parameters specified by (destination) name (e.g. the default name of --input-file is input_file).

Return type:

Callable[[TypeVar(F, bound= Callable[..., Any])], TypeVar(F, bound= Callable[..., Any])]

click_extra.dir_path(*, path_type=<class 'pathlib.Path'>, exists=False, readable=True, writable=False, executable=False, resolve_path=False, allow_dash=False)[source]

Shortcut for click.Path with file_okay=False, path_type=pathlib.Path.

Return type:

Path

click_extra.echo(message=None, file=None, nl=True, err=False, color=None)[source]

Print a message and newline to stdout or a file. This should be used instead of print() because it provides better support for different data, files, and environments.

Compared to print(), this does the following:

  • Ensures that the output encoding is not misconfigured on Linux.

  • Supports Unicode in the Windows console.

  • Supports writing to binary outputs, and supports writing bytes to text outputs.

  • Supports colors and styles on Windows.

  • Removes ANSI color and style codes if the output does not look like an interactive terminal.

  • Always flushes the output.

Parameters:
  • message (object) – The string or bytes to output. Other objects are converted to strings.

  • file (IO[Any] | None) – The file to write to. Defaults to stdout.

  • err (bool) – Write to stderr instead of stdout.

  • nl (bool) – Print a newline after the message. Enabled by default.

  • color (bool | None) – Force showing or hiding colors and other styles. By default Click will remove color if the output does not look like an interactive terminal.

Changed in version 6.0: Support Unicode output on the Windows console. Click does not modify sys.stdout, so sys.stdout.write() and print() will still not support Unicode.

Changed in version 4.0: Added the color parameter.

Added in version 3.0: Added the err parameter.

Changed in version 2.0: Support colors on Windows if colorama is installed.

Return type:

None

click_extra.echo_via_pager(text_or_generator, color=None)[source]

Drop-in for click.echo_via_pager() that streams plainly under –accessible.

A pager is a full-screen, cursor-driven TUI: it traps output behind its own keybindings, hostile to a screen reader consuming a linear stream. Under --accessible the text is written straight to stdout via click.echo() instead. Outside accessibility mode (or with no active context) it defers to click.echo_via_pager(), which already falls back to a plain write when stdout is not a terminal.

The argument is normalized exactly as click.echo_via_pager() does (a generator function is called, a string is emitted as-is, anything else is iterated), so the two behave identically on their inputs.

Return type:

None

click_extra.edit(text=None, editor=None, env=None, require_save=True, extension='.txt', filename=None)[source]
Overloads:
  • text (bytes | bytearray), editor (str | None), env (cabc.Mapping[str, str] | None), require_save (bool), extension (str) → bytes | None

  • text (str), editor (str | None), env (cabc.Mapping[str, str] | None), require_save (bool), extension (str) → str | None

  • text (None), editor (str | None), env (cabc.Mapping[str, str] | None), require_save (bool), extension (str), filename (str | cabc.Iterable[str] | None) → None

Edits the given text in the defined editor. If an editor is given (should be the full path to the executable but the regular operating system search path is used for finding the executable) it overrides the detected editor. Optionally, some environment variables can be used. If the editor is closed without changes, None is returned. In case a file is edited directly the return value is always None and require_save and extension are ignored.

If the editor cannot be opened a UsageError is raised.

Note for Windows: to simplify cross-platform usage, the newlines are automatically converted from POSIX to Windows and vice versa. As such, the message here will have \n as newline markers.

Parameters:
  • text (str | bytes | bytearray | None) – the text to edit.

  • editor (str | None) – optionally the editor to use. Defaults to automatic detection.

  • env (Mapping[str, str] | None) – environment variables to forward to the editor.

  • require_save (bool) – if this is true, then not saving in the editor will make the return value become None.

  • extension (str) – the extension to tell the editor about. This defaults to .txt but changing this might change syntax highlighting.

  • filename (str | Iterable[str] | None) – if provided it will edit this file instead of the provided text contents. It will not use a temporary file as an indirection in that case. If the editor supports editing multiple files at once, a sequence of files may be passed as well. Invoke click.file once per file instead if multiple files cannot be managed at once or editing the files serially is desired.

Changed in version 8.2.0: filename now accepts any Iterable[str] in addition to a str if the editor supports editing multiple files at once.

click_extra.file_path(*, path_type=<class 'pathlib.Path'>, exists=False, readable=True, writable=False, executable=False, resolve_path=False, allow_dash=False)[source]

Shortcut for click.Path with dir_okay=False, path_type=pathlib.Path.

Return type:

Path

click_extra.flatten_config_keys(conf, sep='_', opaque_keys=frozenset({}), _prefix='')[source]

Flatten nested dicts into a single level by joining keys with a separator.

Useful for mapping nested configuration structures (like TOML sub-tables) to flat Python dataclass fields. After normalization with normalize_config_keys, the flattened keys match dataclass field names directly:

>>> from click_extra.config import (
...     flatten_config_keys,
...     normalize_config_keys,
... )
>>> raw = {"dependency-graph": {"all-groups": True, "output": "deps.mmd"}}
>>> flatten_config_keys(normalize_config_keys(raw))
{'dependency_graph_all_groups': True, 'dependency_graph_output': 'deps.mmd'}
Parameters:
  • conf (dict[str, Any]) – Nested dictionary to flatten.

  • sep (str) – Separator used to join parent and child keys. Defaults to "_" which produces valid Python identifiers when combined with normalize_config_keys.

  • opaque_keys (frozenset[str]) – Fully-qualified key names where flattening stops. When the accumulated key matches an entry in this set, the dict value is kept as-is instead of being recursively flattened. This is useful for fields typed as dict[str, X] where the dict keys are data (like GitHub Actions matrix axis names), not config structure.

  • _prefix (str) – Internal parameter for tracking the accumulated key path during recursion. Callers should not set this.

Return type:

dict[str, Any]

click_extra.format_filename(filename, shorten=False)[source]

Format a filename as a string for display. Ensures the filename can be displayed by replacing any invalid bytes or surrogate escapes in the name with the replacement character .

Invalid bytes or surrogate escapes will raise an error when written to a stream with errors="strict". This will typically happen with stdout when the locale is something like en_GB.UTF-8.

Many scenarios are safe to write surrogates though, due to PEP 538 and PEP 540, including:

  • Writing to stderr, which uses errors="backslashreplace".

  • The system has LANG=C.UTF-8, C, or POSIX. Python opens stdout and stderr with errors="surrogateescape".

  • None of LANG/LC_* are set. Python assumes LANG=C.UTF-8.

  • Python is started in UTF-8 mode with PYTHONUTF8=1 or -X utf8. Python opens stdout and stderr with errors="surrogateescape".

Parameters:
  • filename (str | bytes | PathLike[str] | PathLike[bytes]) – formats a filename for UI display. This will also convert the filename into unicode without failing.

  • shorten (bool) – this optionally shortens the filename to strip of the path that leads up to it.

Return type:

str

click_extra.format_param_row(param, ctx, path, is_structured)[source]

Compute the structural table cells for a Click parameter.

Returns a dict[column_id, cell] covering every column that can be derived from the parameter object alone (no runtime invocation state or config-file context). Specifically: id, spec, class, param_type, python_type, hidden, exposed, envvars, default, is_flag, flag_value, is_bool_flag, multiple, nargs, prompt, and confirmation_prompt.

Attributes only defined on click.Option (hidden, is_flag, flag_value, is_bool_flag, prompt, confirmation_prompt) yield None for click.Argument parameters: empty cell in visual formats, null in structured ones.

For structured formats (JSON, YAML, etc.), values are native Python types. For visual formats, values are themed strings matching help-screen styling.

The remaining table columns (allowed_in_conf, value, source) require live context and are filled in by render_params_table().

Return type:

dict[str, Any]

click_extra.get_app_dir(app_name, roaming=True, force_posix=False)[source]

Returns the config folder for the application. The default behavior is to return whatever is most appropriate for the operating system.

To give you an idea, for an app called "Foo Bar", something like the following folders could be returned:

Mac OS X:

~/Library/Application Support/Foo Bar

Mac OS X (POSIX):

~/.foo-bar

Unix:

~/.config/foo-bar

Unix (POSIX):

~/.foo-bar

Windows (roaming):

C:\Users\<user>\AppData\Roaming\Foo Bar

Windows (not roaming):

C:\Users\<user>\AppData\Local\Foo Bar

Added in version 2.0.

Parameters:
  • app_name (str) – the application name. This should be properly capitalized and can contain whitespace.

  • roaming (bool) – controls if the folder should be roaming or not on Windows. Has no effect otherwise.

  • force_posix (bool) – if this is set to True then on any POSIX system the folder will be stored in the home folder with a leading dot instead of the XDG config home or darwin’s application support folder.

Return type:

str

click_extra.get_binary_stream(name)[source]

Returns a system stream for byte processing.

Parameters:

name (Literal['stdin', 'stdout', 'stderr']) – the name of the stream to open. Valid names are 'stdin', 'stdout' and 'stderr'

Return type:

BinaryIO

click_extra.get_current_context(silent=False)[source]
Overloads:
  • Context

  • silent (bool) → Optional[Context]

Equivalent to click.get_current_context() but casts the returned click.Context object to cloup.Context (which is safe when using cloup commands classes and decorators).

click_extra.get_current_theme()[source]

Return the theme active for the current CLI invocation.

Resolution order:

  1. The theme stored on the active Click context under click_extra.context.THEME (set by ThemeOption from --theme).

  2. The process-wide fallback returned by get_default_theme() (the dark default, or whatever patch_click() set at process start).

Falling back through the active context (instead of reading a module attribute) keeps --theme scoped to the invocation that received it, so a second invocation in the same process starts from the default again.

Return type:

HelpTheme

click_extra.get_default_theme()[source]

Return the process-wide fallback theme.

Read by get_current_theme() when no Click context is active or when the active context has no theme set. The default is the built-in dark palette; patch_click() overrides it via set_default_theme() for the duration of a patched session.

Resolved through a function rather than a module attribute so callers always observe the current value: capturing default_theme as a default function parameter (the previous pattern) would freeze whatever was set at import time.

Return type:

HelpTheme

click_extra.get_pager_file(color=None)[source]

Context manager.

Yields a writable file-like object which can be used as an output pager.

Added in version 8.4.0.

Parameters:

color (bool | None) – controls if the pager supports ANSI colors or not. The default is autodetection.

Return type:

ContextManager[TextIO, bool | None]

click_extra.get_param_spec(param, ctx)[source]

Extract the option-spec string (like -v, --verbose) from a parameter.

Temporarily unhides hidden options so their help record can be produced.

Note

The hidden property is only supported by Option, not Argument.

Todo

Submit a PR to Click to separate production of param spec and help record. That way we can always produce the param spec even if the parameter is hidden. See: https://github.com/kdeldycke/click-extra/issues/689

Return type:

str | None

click_extra.get_text_stream(name, encoding=None, errors='strict')[source]

Returns a system stream for text processing. This usually returns a wrapped stream around a binary stream returned from get_binary_stream() but it also can take shortcuts for already correctly configured streams.

Parameters:
  • name (Literal['stdin', 'stdout', 'stderr']) – the name of the stream to open. Valid names are 'stdin', 'stdout' and 'stderr'

  • encoding (str | None) – overrides the detected default encoding.

  • errors (str | None) – overrides the default error mode.

Return type:

TextIO

click_extra.get_tool_config(ctx=None)[source]

Retrieve the typed tool configuration from the context.

Returns the object stored under click_extra.context.TOOL_CONFIG by ConfigOption when a config_schema is set, or None if no schema was configured or no configuration was loaded.

Parameters:

ctx (Context | None) – Click context. Defaults to the current context.

Return type:

Any

click_extra.getchar(echo=False)[source]

Fetches a single character from the terminal and returns it. This will always return a unicode character and under certain rare circumstances this might return more than one character. The situations which more than one character is returned is when for whatever reason multiple characters end up in the terminal buffer or standard input was not actually a terminal.

Note that this will always read from the terminal, even if something is piped into the standard input.

Note for Windows: in rare cases when typing non-ASCII characters, this function might wait for a second character and then return both at once. This is because certain Unicode characters look like special-key markers.

Added in version 2.0.

Parameters:

echo (bool) – if set to True, the character read will also show up on the terminal. The default is to not show it.

Return type:

str

click_extra.group(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.help_option(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.jobs_option(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.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:
Return type:

Parameter | None

click_extra.launch(url, wait=False, locate=False)[source]

This function launches the given URL (or filename) in the default viewer application for this file type. If this is an executable, it might launch the executable in a new session. The return value is the exit code of the launched application. Usually, 0 indicates success.

Examples:

click.launch('https://click.palletsprojects.com/')
click.launch('/my/downloaded/file', locate=True)

Added in version 2.0.

Parameters:
  • url (str) – URL or filename of the thing to launch.

  • wait (bool) – Wait for the program to exit before returning. This only works if the launched program blocks. In particular, xdg-open on Linux does not block.

  • locate (bool) – if this is set to True then instead of launching the application associated with the URL it will attempt to launch a file manager with the file located. This might have weird effects if the URL does not point to the filesystem.

Return type:

int

click_extra.lazy_group(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.make_pass_decorator(object_type, ensure=False)[source]

Given an object type this creates a decorator that will work similar to pass_obj() but instead of passing the object of the current context, it will find the innermost context of type object_type().

This generates a decorator that works roughly like this:

from functools import update_wrapper

def decorator(f):
    @pass_context
    def new_func(ctx, *args, **kwargs):
        obj = ctx.find_object(object_type)
        return ctx.invoke(f, obj, *args, **kwargs)
    return update_wrapper(new_func, f)
return decorator
Parameters:
  • object_type (type[T]) – the type of the object to pass.

  • ensure (bool) – if set to True, a new object will be created and remembered on the context if it’s not there yet.

Return type:

t.Callable[[t.Callable[te.Concatenate[T, P], R]], t.Callable[P, R]]

click_extra.make_schema_callable(schema, *, strict=False, normalize=True)[source]

Wrap a schema type into a callable that accepts a raw config dict.

  • Dataclass types (detected via dataclasses.is_dataclass) are auto-wrapped: keys are normalized (hyphens to underscores), nested dicts are flattened, and the result is filtered to known fields before instantiation. Three schema-aware features refine this process:

    1. Type-aware flattening. Fields typed as dict[str, X] are treated as opaque: flatten_config_keys stops at their boundary so the dict value is kept intact.

    2. Field metadata. Dataclass fields may carry click_extra.config_path (a dotted TOML path like "test-matrix.replace") and click_extra.normalize_keys (False to skip key normalization on the extracted value). Fields with an explicit path are extracted from the raw config before normalization and flattening.

    3. Nested dataclass support. Fields whose resolved type is itself a dataclass are recursively processed with the same logic.

  • Any other callable is returned as-is. The caller is responsible for key normalization if needed.

  • None returns None.

Parameters:
  • strict (bool) – If True, raise ValueError when the config contains keys that do not match any dataclass field (after normalization and flattening).

  • normalize (bool) – If False, skip normalize_config_keys on the remaining config dict. Used internally when recursing into nested dataclasses whose parent opted out of normalization via click_extra.normalize_keys = False.

Return type:

Callable[[dict[str, Any]], Any] | None

click_extra.man_option(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.new_logger(name='root', *, propagate=False, force=True, **kwargs)[source]

Setup a logger in the style of Click Extra.

By default, this helper will:

  • Fetch the logger registered under the name parameter, or creates a new one with that name if it doesn’t exist,

  • Set the logger’s propagate attribute to False,

  • Force removal of any existing handlers and formatters attached to the logger,

  • Attach a new StreamHandler with Formatter,

  • Return the logger object.

This function is a wrapper around basicConfig() and takes the same keywords arguments.

Parameters:
  • name (str) – ID of the logger to setup. If None, Python’s root logger will be used. If a logger with the provided name is not found in the global registry, a new logger with that name will be created.

  • propagate (bool) – Sets the logger’s propagate attribute. Defaults to False.

  • force (bool) – Same as the force parameter from logging.basicConfig() and basicConfig(). Defaults to True.

  • kwargs – Any other keyword parameters supported by logging.basicConfig() and basicConfig().

Return type:

Logger

click_extra.no_color_option(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.no_config_option(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.normalize_config_keys(conf, opaque_keys=frozenset({}), _prefix='')[source]

Normalize configuration keys to valid Python identifiers.

Recursively replaces hyphens with underscores in all dict keys, using the same str.replace("-", "_") transform that Click applies internally when deriving parameter names from option declarations (--foo-bar becomes foo_bar). Click does not expose this as a public function, so we replicate the one-liner here.

Handles the convention mismatch between configuration formats (TOML, YAML, JSON all commonly use kebab-case) and Python identifiers. Works with all configuration formats supported by ConfigOption.

Parameters:
  • opaque_keys (frozenset[str]) – Fully-qualified key names (using "_" as separator) where recursion stops. The key itself is still normalized, but its dict value is kept as-is. Used in tandem with flatten_config_keys’s opaque_keys to protect data dicts (like GitHub Actions matrix axes) from normalization.

  • _prefix (str) – Internal parameter for tracking the accumulated key path during recursion. Callers should not set this.

Todo

Propose upstream to Click to extract the inline name.replace("-", "_") into a private _normalize_param_name helper, so downstream projects like Click Extra can reuse it instead of duplicating the transform.

Return type:

dict[str, Any]

click_extra.open_file(filename, mode='r', encoding=None, errors='strict', lazy=False, atomic=False)[source]

Open a file, with extra behavior to handle '-' to indicate a standard stream, lazy open on write, and atomic write. Similar to the behavior of the File param type.

If '-' is given to open stdout or stdin, the stream is wrapped so that using it in a context manager will not close it. This makes it possible to use the function without accidentally closing a standard stream:

with open_file(filename) as f:
    ...
Parameters:
  • filename (str | PathLike[str]) – The name or Path of the file to open, or '-' for stdin/stdout.

  • mode (str) – The mode in which to open the file.

  • encoding (str | None) – The encoding to decode or encode a file opened in text mode.

  • errors (str | None) – The error handling mode.

  • lazy (bool) – Wait to open the file until it is accessed. For read mode, the file is temporarily opened to raise access errors early, then closed until it is read again.

  • atomic (bool) – Write to a temporary file and replace the given file on close.

Added in version 3.0.

Return type:

IO[Any]

click_extra.option(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.option_group(title, *args, **kwargs)[source]
Overloads:
  • title (str), help (str), options (Decorator), constraint (Optional[Constraint]), hidden (bool) → Callable[[F], F]

  • title (str), options (Decorator), help (Optional[str]), constraint (Optional[Constraint]), hidden (bool) → Callable[[F], F]

Return a decorator that annotates a function with an option group.

The help argument is an optional description and can be provided either as keyword argument or as 2nd positional argument after the name of the group:

# help as keyword argument
@option_group(name, *options, help=None, ...)

# help as 2nd positional argument
@option_group(name, help, *options, ...)

Changed in version 0.9.0: in order to support the decorator cloup.constrained_params(), @option_group now allows each input decorators to add multiple options.

Parameters:
  • title (str) – title of the help section describing the option group.

  • help – an optional description shown below the name; can be provided as keyword argument or 2nd positional argument.

  • options – an arbitrary number of decorators like click.option, which attach one or multiple options to the decorated command function.

  • constraint – an optional instance of Constraint (see Constraints for more info); a description of the constraint will be shown between squared brackets aside the option group title (or below it if too long).

  • hidden – if True, the option group and all its options are hidden from the help page (all contained options will have their hidden attribute set to True).

click_extra.parse_test_plan(plan_string)[source]

Parse a YAML test plan into CLITestCase instances.

The plan must be a YAML list of mappings, each keyed by CLITestCase directive names. Requires the yaml extra.

Raises:
  • ValueError – the plan is empty or a case uses unknown directives.

  • TypeError – the plan is not a list, or a case is not a mapping.

  • ImportError – YAML support is not installed.

Return type:

Generator[CLITestCase, None, None]

click_extra.pass_context(func)[source]

Mark a callback as wanting the active Context as its first argument.

Click’s own click.pass_context() is typed for the base click.Context. A handler annotated with click-extra’s enhanced Context (to reach its extra helpers like ctx.print_table) therefore fails static type checking: function parameters are contravariant, so Callable[[Context], R] is not assignable where a Callable[[click.Context], R] is expected.

This drop-in is typed for the enhanced Context and still accepts handlers typed for the base click.Context (a wider first parameter is allowed), so both type-check. At runtime it forwards the active context unchanged, exactly like click.pass_context().

Return type:

Callable[[ParamSpec(P, bound= None)], TypeVar(R)]

click_extra.pass_obj(f)[source]

Similar to pass_context(), but only pass the object on the context onwards (Context.obj). This is useful if that object represents the state of a nested system.

Return type:

t.Callable[P, R]

click_extra.password_option(*param_decls, **kwargs)[source]

Add a --password option which prompts for a password, hiding input and asking to enter the value again for confirmation.

Parameters:
  • param_decls (str) – One or more option names. Defaults to the single value "--password".

  • kwargs (Any) – Extra arguments are passed to option().

Return type:

Callable[[TypeVar(FC, bound= _AnyCallable | Command)], TypeVar(FC, bound= _AnyCallable | Command)]

click_extra.path(*, path_type=<class 'pathlib.Path'>, exists=False, file_okay=True, dir_okay=True, readable=True, writable=False, executable=False, resolve_path=False, allow_dash=False)[source]

Shortcut for click.Path with path_type=pathlib.Path.

Return type:

Path

click_extra.pause(info=None, err=False)[source]

This command stops execution and waits for the user to press any key to continue. This is similar to the Windows batch “pause” command. If the program is not run through a terminal, this command will instead do nothing.

Added in version 2.0.

Added in version 4.0: Added the err parameter.

Parameters:
  • info (str | None) – The message to print before pausing. Defaults to "Press any key to continue...".

  • err (bool) – if set to message goes to stderr instead of stdout, the same as with echo.

Return type:

None

click_extra.print_data(data, table_format, *, default=None, root_element='records', package='click-extra', **kwargs)[source]

Serialize arbitrary Python data and print it to the console.

Wraps serialize_data() with user-friendly error handling for missing optional dependencies.

Parameters:
  • data (Any) – Arbitrary data to serialize.

  • table_format (TableFormat) – Target serialization format.

  • default (Callable | None) – Fallback serializer for custom types. Defaults to str.

  • root_element (str) – Root element name for XML output.

  • package (str) – Package name for install instructions in error messages.

  • kwargs – Extra keyword arguments forwarded to the underlying serializer.

Return type:

None

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

Render a table and print it to the console.

For markup formats, ANSI color codes are stripped from cell values before rendering unless --color is explicitly set.

Parameters:

sort_key (Callable[[Sequence[str | None]], Any] | None) – Optional callable passed to sorted() as the key argument. When provided, rows are sorted before rendering.

Return type:

None

click_extra.progressbar(iterable=None, length=None, label=None, hidden=None, **kwargs)[source]

Drop-in for click.progressbar() honoring --progress / --no-progress.

Click’s own progress bar is determinate, the counterpart to the indeterminate Spinner. This thin wrapper gates it on the same PROGRESS flag the spinner uses, so a single --no-progress (or --accessible, which lowers the progress default) silences both.

Parameters:

hidden (bool | None) – tri-state. Left at its default None, the bar follows the resolved --progress flag: hidden when the user (or --accessible) turned progress off, shown otherwise. An explicit True or False forces the bar regardless, mirroring how an explicit color= argument overrides ctx.color on click.echo(). With no active context (the bar used outside a Click command) it defaults to shown.

Return type:

ProgressBar[TypeVar(V)]

Note

Only --no-progress is wired here. Color is already handled upstream: Click renders the bar through click.echo(), whose color=None resolves against ctx.color, so --no-color / NO_COLOR strip the bar’s ANSI without any work from this wrapper.

click_extra.prompt(text, default=None, hide_input=False, confirmation_prompt=False, type=None, value_proc=None, prompt_suffix=': ', show_default=True, err=False, show_choices=True)[source]

Prompts a user for input. This is a convenience function that can be used to prompt a user for input later.

If the user aborts the input by sending an interrupt signal, this function will catch it and raise a Abort exception.

Parameters:
  • text (str) – the text to show for the prompt.

  • default (Any | None) – the default value to use if no input happens. If this is not given it will prompt until it’s aborted.

  • hide_input (bool) – if this is set to true then the input value will be hidden.

  • confirmation_prompt (bool | str) – Prompt a second time to confirm the value. Can be set to a string instead of True to customize the message.

  • type (ParamType[Any] | Any | None) – the type to use to check the value against.

  • value_proc (Callable[[str], Any] | None) – if this parameter is provided it’s a function that is invoked instead of the type conversion to convert a value.

  • prompt_suffix (str) – a suffix that should be added to the prompt.

  • show_default (bool | str) – shows or hides the default value in the prompt. If this value is a string, it shows that string in parentheses instead of the actual value.

  • err (bool) – if set to true the file defaults to stderr instead of stdout, the same as with echo.

  • show_choices (bool) – Show or hide choices if the passed type is a Choice. For example if type is a Choice of either day or week, show_choices is true and text is “Group by” then the prompt will be “Group by (day, week): “.

Changed in version 8.3.3: show_default can be a string to show a custom value instead of the actual default, matching the help text behavior.

Changed in version 8.3.1: A space is no longer appended to the prompt.

Added in version 8.0: confirmation_prompt can be a custom string.

Added in version 7.0: Added the show_choices parameter.

Added in version 6.0: Added unicode support for cmd.exe on Windows.

Added in version 4.0: Added the err parameter.

Return type:

Any

click_extra.quiet_option(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.register_theme(name, theme)[source]

Register a named theme in the module-level theme_registry.

Parameters:
  • name (str) – Lowercase identifier used as the --theme choice value.

  • theme (HelpTheme) – A HelpTheme instance.

Return type:

None

click_extra.render_columns_markdown_table(columns)[source]

Render an iterable of ColumnSpec as a 2-column Markdown table.

Output shape:

| Column | Description |
| :--- | :--- |
| `Label` | description |
...

Suitable for inlining into MyST documents via myst_substitutions so the Available columns reference can be auto-generated from a single source of truth.

Return type:

str

click_extra.render_manpage(command, prog_name=None, ctx=None, **overrides)[source]

Render a single command’s man page as a roff string.

Reuses ctx when given (like the live invocation context), otherwise builds a throwaway one with resilient_parsing=True. Keyword overrides (version, date, manual, authors, copyright) are passed through to extract_manpage().

Return type:

str

click_extra.render_manpages(command, prog_name=None, **overrides)[source]

Render the whole command tree, one man page per (sub)command.

Returns an ordered mapping of {filename: roff} where each filename is the command path joined by hyphens plus the section suffix (like weather-forecast.1).

Return type:

dict[str, str]

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

Render a table and return it as a string.

Parameters:

sort_key (Callable[[Sequence[str | None]], Any] | None) – Optional callable passed to sorted() as the key argument. When provided, rows are sorted before rendering.

Return type:

str

click_extra.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[TypeVar(P, bound= Parameter)]) – the sibling parameter class to look for.

Return type:

TypeVar(P, bound= Parameter)

click_extra.run_config_validation(user_conf, *, app_name, params_template, config_schema=None, config_validators=(), fallback_sections=(), schema_strict=False, strict=False, collect_all=True)[source]

Validate a parsed configuration document in one schema-driven pass.

This is the module-level entry point that unifies click-extra’s three historical validation paths (CLI-parameter strict check, dataclass schema, and app-registered ConfigValidator hooks) behind a single function yielding a single error type. It is deliberately not named validate_config: that name belongs to validate_config(), the callback powering the --validate-config flag.

Stages, in order:

  1. Normalize. Strip reserved keys and expand dotted keys.

  2. Partition. Split opaque sub-trees (schema extension fields plus every registered validator’s extension_path) from the CLI-flag-bound content. Extracted sub-trees land in ValidationReport.opaque_subtrees.

  3. Strict-check the CLI-flag-bound part against params_template, keeping the merged result as ValidationReport.merged_conf (skipped when params_template is None).

  4. Schema-build the app section through the configured callable, producing ValidationReport.schema_instance.

  5. Validate every opaque sub-tree through its registered validator.

Parameters:
  • user_conf (dict[str, Any]) – The full parsed configuration document.

  • app_name (str) – Name of the app’s section (used to resolve the section and to root opaque paths and error paths at the document level).

  • params_template (dict[str, Any] | None) – The CLI-parameter template the strict check runs against. Pass None to skip the strict check entirely (for example, for a schema-only validation).

  • config_schema (type | Callable[[dict[str, Any]], Any] | None) – Dataclass type or callable describing the typed configuration, or None.

  • config_validators (Sequence[ConfigValidator]) – Extension validators to run against opaque sub-trees.

  • fallback_sections (Sequence[str]) – Legacy section names to try when app_name is absent or empty.

  • schema_strict (bool) – Reject keys the dataclass schema does not recognize.

  • strict (bool) – Reject keys the CLI-parameter template does not recognize.

  • collect_all (bool) – When True (default), run every stage and collect all errors. When False, the first error short-circuits the rest.

Return type:

ValidationReport

Returns:

A ValidationReport. ValidationError is the single error type recorded by every stage; ValueError / TypeError raised by the strict check or schema callable are wrapped into it.

click_extra.run_jobs(func, items, *, jobs=None)[source]

Run func over items, parallelized per the resolved --jobs count.

The worker count is taken from jobs when given, else from the active command’s JobsOption value (ctx.meta[click_extra.context.JOBS]), else 1. With a single worker (or at most one item) the items run sequentially and lazily, so a caller can stop early on the first result (for example to abort on the first failure); otherwise they run in a thread pool. Either way results are yielded in submission order, like map().

The pool is thread-based, which suits the I/O- and subprocess-bound work CLI tools usually parallelize (each child releases the GIL). The count is a number of logical CPUs: see CPU_COUNT.

Parameters:
  • func (Callable[[TypeVar(T)], TypeVar(R)]) – Called once per item; its return value is yielded.

  • items (Iterable[TypeVar(T)]) – The work items. Materialized up front to size the pool.

  • jobs (int | None) – Override the worker count instead of reading it from the context. 1 or fewer forces sequential execution.

Return type:

Iterator[TypeVar(R)]

Returns:

An iterator over func’s results, in the order of items.

click_extra.run_test_plan(command, cases, *, jobs=1, select_test=None, skip_platform=None, timeout=None, exit_on_error=False, show_trace_on_error=True, stats=True, show_progress=True)[source]

Run a list of test cases against a target command and tally the results.

Cases are parallelized per jobs (see click_extra.execution.run_jobs()): at one worker they run sequentially and lazily, so exit_on_error can stop before the rest start; otherwise they run in a thread pool and every case runs to completion. Either way outcomes are tallied in submission order. On an interactive terminal a click_extra.spinner.Spinner reports progress unless show_progress is false.

Parameters:
  • command (Path | str) – The target to test: a command name, a command line, or a path to a binary or script.

  • cases (Sequence[CLITestCase]) – The test cases to run.

  • jobs (int) – Number of parallel workers; 1 runs sequentially.

  • select_test (Sequence[int] | None) – 1-based case numbers to run; others are skipped.

  • skip_platform (Trait | Group | str | None | Iterable[Trait | Group | str | None | Iterable[Trait | Group | str | None | Iterable[Trait | Group | str | None | Iterable[_TNestedReferences]]]]) – Extra platforms (or group IDs) to skip every case on.

  • timeout (float | None) – Default per-case timeout in seconds when a case sets none.

  • exit_on_error (bool) – Stop at the first failure (sequential runs only).

  • show_trace_on_error (bool) – Echo the execution trace of each failed case.

  • stats (bool) – Echo a one-line worker summary up front and a result tally.

  • show_progress (bool) – Allow the progress spinner on an interactive terminal.

Return type:

Counter

Returns:

A collections.Counter with total, skipped, and failed keys. A non-zero failed count signals the caller to exit with an error.

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

Search a particular class of parameter in a list and return them.

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

  • klass (type[Parameter]) – the class of the parameters to look for.

  • include_subclasses (bool) – if True, includes in the results all parameters subclassing the provided klass. If False, only matches parameters which are strictly instances of klass. Defaults to True.

  • unique (bool) – if True, raise an error if more than one parameter of the provided klass is found. Defaults to True.

Return type:

list[Parameter] | Parameter | None

click_extra.secho(message=None, file=None, nl=True, err=False, color=None, **styles)[source]

This function combines echo() and style() into one call. As such the following two calls are the same:

click.secho('Hello World!', fg='green')
click.echo(click.style('Hello World!', fg='green'))

All keyword arguments are forwarded to the underlying functions depending on which one they go with.

Non-string types will be converted to str. However, bytes are passed directly to echo() without applying style. If you want to style bytes that represent text, call bytes.decode() first.

Changed in version 8.0: A non-string message is converted to a string. Bytes are passed through without style applied.

Added in version 2.0.

Return type:

None

click_extra.select_columns(columns, selected_ids)[source]

Filter and reorder columns according to selected_ids.

Returns columns unchanged when selected_ids is falsy (no projection). Otherwise yields the matching ColumnSpec in the order selected_ids specifies, SQL-SELECT-style. Raises KeyError for unknown IDs so the caller can convert it into a click.UsageError.

Return type:

tuple[ColumnSpec, ...]

click_extra.select_row(row, selected_ids, canonical_ids)[source]

Build a positional row by reading cells from row in the selection order.

Falls back to canonical_ids when selected_ids is empty / unset, so the row preserves its canonical column order in the absence of any user selection.

Return type:

tuple

click_extra.serialize_data(data, table_format, *, default=None, root_element='records', **kwargs)[source]

Serialize arbitrary Python data to a structured format.

Unlike render_table() which expects tabular rows and headers, this function accepts any JSON-compatible data structure (dicts, lists, nested combinations) and serializes it to the requested format.

Only formats in SERIALIZATION_FORMATS are supported.

Parameters:
  • data (Any) – Arbitrary data to serialize (dicts, lists, scalars).

  • table_format (TableFormat) – Target serialization format.

  • default (Callable | None) – Fallback serializer for types not natively supported. Defaults to str, so Path and similar types are stringified automatically. Set to a custom callable for different behavior.

  • root_element (str) – Root element name for XML output.

  • kwargs – Extra keyword arguments forwarded to the underlying serializer (like sort_keys or indent for JSON).

Raises:

ValueError – If the format is not a serialization format.

Return type:

str

click_extra.set_default_theme(theme)[source]

Override the process-wide fallback theme.

ThemeOption writes its picked theme to ctx.meta rather than calling this helper, so per-invocation choices do not leak across invocations sharing the same process. Use this only for genuinely process-wide overrides: patch_click() is the canonical caller.

Return type:

None

click_extra.show_params_option(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.style(text, fg=None, bg=None, bold=None, dim=None, underline=None, overline=None, italic=None, blink=None, reverse=None, strikethrough=None, reset=True)[source]

Styles a text with ANSI styles and returns the new string. By default the styling is self contained which means that at the end of the string a reset code is issued. This can be prevented by passing reset=False.

Examples:

click.echo(click.style('Hello World!', fg='green'))
click.echo(click.style('ATTENTION!', blink=True))
click.echo(click.style('Some things', reverse=True, fg='cyan'))
click.echo(click.style('More colors', fg=(255, 12, 128), bg=117))

Supported color names:

  • black (might be a gray)

  • red

  • green

  • yellow (might be an orange)

  • blue

  • magenta

  • cyan

  • white (might be light gray)

  • bright_black

  • bright_red

  • bright_green

  • bright_yellow

  • bright_blue

  • bright_magenta

  • bright_cyan

  • bright_white

  • reset (reset the color code only)

If the terminal supports it, color may also be specified as:

  • An integer in the interval [0, 255]. The terminal must support 8-bit/256-color mode.

  • An RGB tuple of three integers in [0, 255]. The terminal must support 24-bit/true-color mode.

See https://en.wikipedia.org/wiki/ANSI_color and https://gist.github.com/XVilka/8346728 for more information.

Parameters:
  • text (Any) – the string to style with ansi codes.

  • fg (int | tuple[int, int, int] | str | None) – if provided this will become the foreground color.

  • bg (int | tuple[int, int, int] | str | None) – if provided this will become the background color.

  • bold (bool | None) – if provided this will enable or disable bold mode.

  • dim (bool | None) – if provided this will enable or disable dim mode. This is badly supported.

  • underline (bool | None) – if provided this will enable or disable underline.

  • overline (bool | None) – if provided this will enable or disable overline.

  • italic (bool | None) – if provided this will enable or disable italic.

  • blink (bool | None) – if provided this will enable or disable blinking.

  • reverse (bool | None) – if provided this will enable or disable inverse rendering (foreground becomes background and the other way round).

  • strikethrough (bool | None) – if provided this will enable or disable striking through text.

  • reset (bool) – by default a reset-all code is added at the end of the string which means that styles do not carry over. This can be disabled to compose styles.

Changed in version 8.0: A non-string message is converted to a string.

Changed in version 8.0: Added support for 256 and RGB color codes.

Changed in version 8.0: Added the strikethrough, italic, and overline parameters.

Changed in version 7.0: Added support for bright colors.

Added in version 2.0.

Return type:

str

click_extra.table_format_option(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.telemetry_option(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.theme_option(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.timer_option(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.unstyle(text)[source]

Removes ANSI styling information from a string. Usually it’s not necessary to use this function as Click’s echo function will automatically remove styling if necessary.

Added in version 2.0.

Parameters:

text (str) – the text to remove style information from.

Return type:

str

click_extra.validate_config_option(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.verbose_option(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.verbosity_option(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.version_option(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.wrap_text(text, width=78, initial_indent='', subsequent_indent='', preserve_paragraphs=False)[source]

A helper function that intelligently wraps text. By default, it assumes that it operates on a single paragraph of text but if the preserve_paragraphs parameter is provided it will intelligently handle paragraphs (defined by two empty lines).

If paragraphs are handled, a paragraph can be prefixed with an empty line containing the \b character (\x08) to indicate that no rewrapping should happen in that block.

Parameters:
  • text (str) – the text that should be rewrapped.

  • width (int) – the maximum width for the text.

  • initial_indent (str) – the initial indent that should be placed on the first line as a string.

  • subsequent_indent (str) – the indent string that should be placed on each consecutive line.

  • preserve_paragraphs (bool) – if this flag is set then the wrapping will intelligently handle paragraphs.

Changed in version 8.4.0: Width is measured in visible characters. ANSI escape sequences in text, initial_indent, or subsequent_indent no longer count toward the width budget, so styled input wraps based on what the user sees instead of raw byte length.

Return type:

str

click_extra.write_manpages(command, target_dir, prog_name=None, **overrides)[source]

Render the command tree and write each man page into target_dir.

Creates target_dir if missing. Returns the list of written paths.

Return type:

list[Path]

click_extra.zero_exit_option(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

Subpackages

Submodules

click_extra.cli module

Click Extra CLI with pre-baking utilities.

click_extra.cli_wrapper module

The click-extra wrap command and the machinery to wrap a foreign Click CLI.

Monkey-patches Click’s decorator functions before importing (or running) a target module so its @click.command() / @click.group() produce colorized, keyword-highlighted, themed variants. Also resolves and invokes the target, and introspects it for --show-params and --man without firing its callbacks.

Not to be confused with text wrapping: that is click.wrap_text(), exposed at the package root as click_extra.wrap_text.

class click_extra.cli_wrapper.WrapperGroup(*args, help_command=True, **kwargs)[source]

Bases: Group

Group that falls back to the wrap subcommand for unknown names.

Known subcommands and their aliases are dispatched normally. Anything else is treated as a target script and forwarded to wrap.

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.

resolve_command(ctx, args)[source]
Return type:

tuple[str | None, Command | None, list[str]]

click_extra.cli_wrapper.patch_click(theme=None, color=True)[source]

Replace Click’s decorator functions with colorized variants.

Must be called before importing the target CLI module so that @click.command() and @click.group() decorators produce colorized commands.

Note

Only the decorator functions are replaced, not the class names (click.Command, click.Group). Replacing class names would break isinstance and issubclass checks in Click internals (_param_memo) and Cloup’s decorator validators.

Parameters:
  • theme (HelpTheme | None) – Color theme to use. None keeps the current default.

  • color (bool | None) – Tri-state ANSI control mirroring ctx.color: True forces colors on, False strips them, and None (the GNU auto default) defers to the output stream’s TTY status.

Return type:

None

click_extra.cli_wrapper.unpatch_click()[source]

Restore Click’s original decorator functions and methods.

Reverses the changes made by patch_click(). Useful in tests to avoid leaking global state between test cases.

Return type:

None

click_extra.cli_wrapper.resolve_target(script)[source]

Resolve a script name to a module path and function name.

Resolution order:

  1. console_scripts entry points from installed packages.

  2. Explicit module:function notation.

  3. .py file path.

  4. Bare Python module or package name.

Return type:

tuple[str, str]

Returns:

(module_path, function_name) tuple. function_name is empty when the target should be invoked as a module or script file.

Raises:

click.ClickException – If the script cannot be resolved.

click_extra.cli_wrapper.invoke_target(script, module_path, function_name, args)[source]

Import and call the target CLI.

Reconstructs sys.argv so Click’s argument parsing sees the target’s program name and arguments.

Parameters:
  • script (str) – Original script name (used as sys.argv[0]).

  • module_path (str) – Dotted module path or .py file path.

  • function_name (str) – Function to call, or empty for module execution.

  • args (tuple[str, ...]) – Arguments to pass to the target CLI.

Return type:

None

click_extra.cli_wrapper.resolve_target_command(script, subcommands=())[source]

Import SCRIPT and return its Click command object and a matching context.

Resolves SCRIPT through resolve_target(), imports the module, then obtains the command object without running the CLI: the entry-point attribute when it is itself a command, otherwise by scanning the module’s namespace for Click command instances (preferring groups). Optional subcommands navigate into nested groups, mirroring the path a user would type.

Shared by the wrap command’s --show-params and --man modes so both introspect the exact same resolved command.

Raises:

click.ClickException – when no unambiguous Click command can be found, or a requested subcommand does not exist.

Return type:

tuple[Command, Context]

click_extra.color module

Resolve whether terminal output should be colored.

Owns the --color[=WHEN] and --no-color options, the color environment variables (NO_COLOR, FORCE_COLOR, CLICOLOR, and friends), and the tri-state WHEN resolution. The actual styling lives elsewhere: click_extra.styling (the Style primitive), click_extra.theme (palettes), and click_extra.highlight (help-screen rendering).

click_extra.color.color_envvars = {'CLICOLOR': True, 'CLICOLORS': True, 'CLICOLORS_FORCE': True, 'CLICOLOR_FORCE': True, 'COLOR': True, 'COLORS': True, 'FORCE_COLOR': True, 'FORCE_COLORS': True, 'LLM': False, 'NOCOLOR': False, 'NOCOLORS': False, 'NO_COLOR': False, 'NO_COLORS': False}

List of environment variables recognized as flags to switch color rendering on or off.

The key is the name of the variable and the boolean value the value to pass to --color option flag when encountered.

Source:

click_extra.color.COLOR_DISABLING_TERMS = frozenset({'dumb', 'unknown'})

TERM values marking a terminal too limited for ANSI niceties.

A dumb or unknown terminal advertises neither SGR color nor the cursor-control codes (carriage return, clear-line) an animation relies on, so both Click Extra’s color resolution (resolve_color_env()) and the spinner’s animation gating (Spinner._resolve_enabled) treat these two values as a hard opt-out. Sharing the set keeps the color and animation axes from drifting apart.

An unset TERM is deliberately excluded: it is common on legitimately color-capable streams (subprocesses, some IDEs) where defaulting to off would be a regression. This matches Rich, which keys its own dumb-terminal detection on the same two values and not on absence.

click_extra.color.resolve_color_env()[source]

Reconcile the recognized color environment variables into a tri-state.

Inspects every variable listed in color_envvars and returns:

  • True if at least one enabling variable (FORCE_COLOR, CLICOLOR, …) is set. Enabling wins over disabling, so a single one is enough to keep colors.

  • False if only disabling variables (NO_COLOR, LLM, …) are set.

  • None when no recognized variable is present, leaving the caller free to apply its own default (typically auto).

A bare variable (no value), or one whose value cannot be parsed as a boolean, counts as activation, in the permissive spirit of the NO_COLOR and FORCE_COLOR conventions.

A dumb or unknown TERM (see COLOR_DISABLING_TERMS) casts a disabling vote as well, so a terminal that cannot render ANSI is treated as color-off even when it still reports as a TTY. Because enabling wins, an explicit FORCE_COLOR stays authoritative over it.

Return type:

bool | None

click_extra.color.forced_color()[source]

Force ANSI color while Click Extra captures CLI text for documentation.

Click Extra renders CLI help and output into docs from both the MkDocs plugin (click_extra.mkdocs) and the Sphinx directives (click_extra.sphinx.click). During a build that output is a pipe, not a TTY, so the underlying renderers strip their escape codes. Two independent color systems have to be defeated:

  • Click’s, gated by should_strip_ansi / ctx.color (what click.echo and the Click and Click Extra help formatters consult). Sphinx’s runner additionally flips this one with click.testing.CliRunner(color=True).

  • Rich’s, gated by rich.console.Console.is_terminal, which ignores the above and reads FORCE_COLOR (https://force-color.org). This is the system rich-click uses, and color=True never reaches it.

FORCE_COLOR is the only signal common to both systems (Rich reads it directly; Click Extra recognizes it through color_envvars), so it is the lever we set here. We also clear the color-disabling variables Click Extra recognizes (NO_COLOR, LLM, …) so an opt-out in the build environment cannot suppress the rendering, and pin COLORTERM=truecolor so the branded 24-bit themes render at full depth instead of being quantized to the 256-color palette (see supports_truecolor()). The previous environment is restored on exit, so the override never leaks beyond a single capture.

Return type:

Iterator[None]

click_extra.color.COLOR_WHEN = ('auto', 'always', 'never')

GNU-canonical tri-state values accepted by --color=<WHEN>.

auto defers to terminal detection, always forces ANSI on, never strips it. See GNU coreutils and this discussion.

click_extra.color.COLOR_WHEN_ALIASES: dict[str, str] = {'force': 'always', 'if-tty': 'auto', 'no': 'never', 'none': 'never', 'tty': 'auto', 'yes': 'always'}

GNU coreutils synonyms accepted as hidden aliases for each COLOR_WHEN value.

GNU ls accepts yes/force for always, no/none for never and tty/if-tty for auto, alongside the three canonical spellings (see COLOR_WHEN). Click Extra mirrors that leniency but keeps the synonyms out of --help output, error messages and shell completion, which only ever advertise COLOR_WHEN.

class click_extra.color.ColorWhenChoice(choices, case_sensitive=True)[source]

Bases: Choice

click.Choice over COLOR_WHEN that also accepts the hidden GNU synonyms (COLOR_WHEN_ALIASES) and native configuration booleans, folding them to a canonical value before validation.

Only the three canonical COLOR_WHEN values reach --help, error messages and shell completion, because the public choices stay canonical. Synonyms and booleans are accepted silently and normalized, so downstream code (ColorOption.set_color(), _WHEN_TO_TRISTATE) only ever sees auto, always or never.

Matching is case-insensitive and whitespace-tolerant, which also makes the canonical values forgiving, such as --color=ALWAYS.

convert(value, param, ctx)[source]

Fold synonyms and booleans to canonical, then defer to click.Choice.

A native bool only reaches this method from a structured configuration file: TOML or JSON booleans, or YAML’s coercion of yes/no/on/off/true/false. True maps to always and False to never, consistent with a bare --color and --no-color. The command line always delivers strings, so this never turns --color=true into a valid CLI spelling.

Caution

A configuration boolean therefore diverges from git’s color.ui, where true means auto. Click Extra keeps true equal to always so the yes string synonym and YAML’s coercion of yes to True resolve identically across file formats.

Return type:

Any

class click_extra.color.ColorOption(param_decls=None, is_flag=False, flag_value='always', default='auto', is_eager=True, expose_value=False, help='Colorize the output. A bare --color is the same as --color=always.', **kwargs)[source]

Bases: ExtraOption

A pre-configured --color[=WHEN] tri-state option.

Mirrors the GNU coreutils convention: WHEN is one of COLOR_WHEN (auto, always or never), and a bare --color (no value) means always. The negative alias --no-color is carried by the separate NoColorOption, because Click forbids attaching /--no-x secondary flags to a value option.

The resolved tri-state lands on ctx.color, the Click-standard attribute that echo() reads through its resolve_color_default()should_strip_ansi() chain: True keeps ANSI codes, False strips them, None (auto) defers to the output stream’s TTY status.

This option is eager by default, so other eager options (like --version) are rendered with the resolved color state.

Note

--color is deliberately not wired to an envvar. The color environment variables (NO_COLOR, FORCE_COLOR, …) are read manually through resolve_color_env(). Letting Click manage them would dump the whole color_envvars set into the --show-params env-var column, and only bind one variable per option anyway.

add_to_parser(parser, ctx)[source]

Register the option, then teach the parser GNU optional-argument rules.

Click’s optional-value parser binds --color to the next token whenever it does not look like an option, so mycli --color subcommand would consume subcommand as the color value and fail. GNU instead binds an optional argument only when it is attached with =.

This wraps the parser’s long-option matcher so a bare --color replays as --color=<flag_value> (always) and leaves the following argument untouched, while --color=<when> keeps working. The wrapper stays inert for every option that does not carry _gnu_optional_value, so it is safe to install on the shared parser.

Return type:

None

set_color(ctx, param, value)[source]

Resolve --color=<WHEN> against the environment and pin ctx.color.

Precedence, highest first:

  1. An explicit --color on the command line.

  2. The color environment variables, but only when the value comes from the built-in default. A configuration file or --accessible (both seen here as a non-DEFAULT source) therefore wins over the environment, matching AccessibleOption.

  3. A color state already pinned by --no-color, a forced test runner, or an explicit Context(color=...): preserved when this option only resolves to auto from its default.

  4. The auto default, leaving ctx.color at None for TTY detection.

Return type:

None

class click_extra.color.NoColorOption(param_decls=None, is_flag=True, default=False, is_eager=True, expose_value=False, help='Disable colorization (alias of --color=never).', **kwargs)[source]

Bases: ExtraOption

--no-color flag that forces --color=never.

Click rejects /--no-x secondary flags on a value option, so the negative alias of the tri-state ColorOption cannot live on it and is provided here as a standalone boolean flag. When set, it pins ctx.color to False; when absent it is a no-op, leaving the resolution to ColorOption.

Shown on its own line directly below --color (mirroring --no-config below --config), since every other negative in the default option set is visible too. Eager by default, like ColorOption, so the color state is settled before other eager options render.

set_no_color(ctx, param, value)[source]

Force ctx.color off when a negative alias is passed; no-op otherwise.

Return type:

None

click_extra.commands module

Wraps vanilla Click and Cloup commands with extra features.

Our flavor of commands, groups and context are all subclasses of their vanilla counterparts, but are pre-configured with good and common defaults. You can still use the mixins in here to build up your own custom variants.

click_extra.commands.default_params()[source]

Default additional options added to @command and @group.

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 CONFIG_PATH

    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 CONFIG_PATH

  5. --accessible

    Hint

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

  6. --color / --no-color

  7. --progress / --no-progress

  8. --theme

  9. --show-params

  10. --table-format FORMAT

  11. --verbosity LEVEL

  12. -v, --verbose

  13. -q, --quiet

  14. --man

  15. --version

  16. -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.

Todo

For bullet-proof handling of edge-cases, we should probably add an indirection layer to have the processing order of options (the one below) different from the presentation order of options in the help screen.

This is probably something that has been requested in issue #544.

Return type:

list[Option]

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.Command(*args, version_fields=None, config_schema=None, schema_strict=False, fallback_sections=(), config_validators=(), included_params=None, extra_option_at_end=True, populate_auto_envvars=True, extra_keywords=None, excluded_keywords=None, **kwargs)[source]

Bases: _HelpColorsMixin, Command

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

List of extra parameters:

Parameters:
  • 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.

  • 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.

  • 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.

  • populate_auto_envvars (bool) – forces all parameters to have their auto-generated environment variables registered. This address the shortcoming of click which only evaluates them dynamically. By forcing their registration, the auto-generated environment variables gets displayed in the help screen, fixing click#2483 issue. On Windows, environment variable names are case-insensitive, so we normalize them 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 --show-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

context_settings: dict[str, Any]

an optional dictionary with defaults passed to the context.

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.

Return type:

Any

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

Intercept the call to the original click.core.Command.make_context so we can keep a copy of the raw, pre-parsed arguments provided to the CLI.

The result are passed to our own Context constructor which is able to initialize the context’s meta property under our own click_extra.context.RAW_ARGS entry. This will be used in ShowParamsOption.print_params() to print the table of parameters fed to the CLI.

See also

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

Return type:

Any

parse_args(ctx, args)[source]

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

Also settles the color options before delegating, so --color / --no-color colorize the eager help and version screens regardless of their position on the command line. See _resolve_color_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, 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).

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, 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: ColorizedCommand

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, **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.

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

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

Like cloup.Group.add_command, but replaces an auto-injected HelpCommand when the user registers their own help subcommand.

Return type:

None

invoke(ctx)[source]

Inject _default_subcommands and _prepend_subcommands from config.

If the user has not provided any subcommands explicitly, and the loaded configuration contains a _default_subcommands list for this group, those subcommands are injected into ctx.protected_args so that Click’s normal Group.invoke() dispatches them.

_prepend_subcommands always prepends subcommands to the invocation, regardless of whether CLI subcommands were provided. Only works with chain=True groups.

Return type:

Any

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"}
lazy_subcommands: dict[str, str]
list_commands(ctx)[source]

List all commands, including not-yet-loaded lazy subcommands.

Return type:

list[str]

get_command(ctx, cmd_name)[source]

Get a command by name, loading lazily if necessary.

Todo

Allow passing extra parameters to the self.lazy_subcommands so we can register commands with custom settings like Cloup’s section or fallback_to_default_section:

  • section: Section | None = None,

  • fallback_to_default_section: bool = True,

See: https://github.com/janluke/cloup/blob/master/cloup/_sections.py#L169

Return type:

Command | None

click_extra.decorators module

Decorators for group, commands and options.

click_extra.decorators.allow_missing_parenthesis(dec_factory)[source]

Allow to use decorators with or without parenthesis.

As proposed in Cloup issue #127.

click_extra.decorators.decorator_factory(dec, *new_args, **new_defaults)[source]

Clone decorator with a set of new defaults.

Used to create our own collection of decorators for our custom options, based on Cloup’s.

Attention

The cls argument passed to the factory is used as the reference class from which the produced decorator’s cls argument must inherit.

The idea is to ensure that, for example, the @command decorator re-implemented by Click Extra is always a subclass of Command, even when the user overrides the cls argument. That way it can always rely on the additional properties and methods defined in the Click Extra framework, where we have extended Cloup and Click so much that we want to prevent surprising side effects.

click_extra.decorators.command(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.group(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.option(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.argument(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.help_option(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.version_option(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.lazy_group(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.accessible_option(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.color_option(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.columns_option(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.config_option(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.jobs_option(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.man_option(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.no_color_option(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.no_config_option(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.quiet_option(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.validate_config_option(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.show_params_option(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.table_format_option(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.telemetry_option(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.theme_option(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.timer_option(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.verbose_option(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.verbosity_option(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.decorators.zero_exit_option(*args, **kwargs)

Returns a new decorator instantiated with custom defaults.

These defaults values are merged with the user’s own arguments.

A special case is made for the params argument, to allow it to be callable. This limits the issue of the mutable options being shared between commands.

This decorator can be used with or without arguments.

click_extra.envvar module

Implements environment variable utilities.

click_extra.envvar.TEnvVarID = str | None

Type of environment variable names.

click_extra.envvar.TNestedEnvVarIDs

Type for arbitrary nested environment variable names.

alias of Iterable[str | None | Iterable[TNestedEnvVarIDs]]

click_extra.envvar.TEnvVars

Type for dict-like environment variables.

alias of Mapping[str, str | None]

click_extra.envvar.merge_envvar_ids(*envvar_ids)[source]

Merge and deduplicate environment variables.

Multiple parameters are accepted and can be single strings or arbitrary-nested iterables of strings. None values are ignored.

Variable names are deduplicated while preserving their initial order.

Returns a tuple of strings. The result is ready to be used as the envvar parameter for Click’s options or arguments.

Return type:

tuple[str, ...]

click_extra.envvar.clean_envvar_id(envvar_id)[source]

Utility to produce a user-friendly environment variable name from a string.

Separates all contiguous alphanumeric string segments, eliminate empty strings, join them with an underscore and uppercase the result.

Attention

We do not rely too much on this utility to try to reproduce the current behavior of Click, which is not consistent regarding case-handling of environment variable.

Return type:

str

click_extra.envvar.param_auto_envvar_id(param, ctx)[source]

Compute the auto-generated environment variable of an option or argument.

Returns the auto envvar exactly as computed within Click’s internals, by click.core.Parameter.resolve_envvar_value() and click.core.Option.resolve_envvar_value().

Return type:

str | None

click_extra.envvar.param_envvar_ids(param, ctx)[source]

Returns the deduplicated, ordered list of environment variables for an option or argument, including the auto-generated one.

The auto-generated environment variable is added at the end of the list, so that user-defined envvars takes precedence. This respects the current implementation of click.core.Option.resolve_envvar_value().

Names are normalized to uppercase on Windows by merge_envvar_ids().

Return type:

tuple[str, ...]

click_extra.envvar.env_copy(extend=None)[source]

Returns a copy of the current environment variables and eventually extend it.

Mimics Python’s original implementation by returning None if no extend content are provided.

Environment variables are expected to be a dict of str:str.

Return type:

Mapping[str, str | None] | None

click_extra.execution module

Options controlling how a CLI runs: timing, parallelism and exit code.

These options share the same shape: each is a pre-configured ExtraOption that publishes its resolved value on ctx.meta for downstream code to consume. Only TimerOption acts on its own (printing the elapsed time); JobsOption and ZeroExitOption are contracts the framework records but does not enforce.

click_extra.execution.CPU_COUNT = 1

Number of logical CPUs available, or None if undetermined.

This is os.cpu_count(), which counts logical processors (hardware threads). On a CPU with simultaneous multi-threading (Intel Hyper-Threading, AMD SMT) a 4-physical-core chip reports 8. It is therefore not a count of physical cores, and is usually larger than what physical-core tools report, such as psutil.cpu_count(logical=False) or pytest-xdist’s -n auto (which counts physical cores). Parallelism here is keyed on the logical count on purpose: subprocess- and I/O-bound work overlaps well across hardware threads.

click_extra.execution.DEFAULT_JOBS = 1

Default number of parallel jobs: one fewer than CPU_COUNT (logical CPUs).

Leaves one logical CPU free for the main process and system tasks. Falls back to 1 (sequential) when the count cannot be determined.

Caution

This resolves to 1 not only on single-core hosts but also on two-core hosts, since it reserves one core. There, the default silently runs sequentially. JobCount.convert() logs a warning whenever a parallel-intent keyword collapses to a single job this way.

class click_extra.execution.JobCount[source]

Bases: ParamType

Parse a --jobs value: an integer or the auto/max keyword.

Resolves the symbolic keywords against the host’s logical CPU count (CPU_COUNT), counting hardware threads, not physical cores:

  • auto resolves to DEFAULT_JOBS (one fewer than the available logical CPUs), the same heuristic used as the option’s default.

  • max resolves to CPU_COUNT (every available logical CPU).

Any other token is parsed as an integer and left to JobsOption.validate_jobs() for clamping and range-checking. Resolving the keywords here keeps the value handed downstream a plain int, so consumers never have to know about the keywords.

name: str = 'jobs'

the descriptive name of this type

choices = ('auto', 'max')

Symbolic keywords accepted besides an integer count, in render order.

Exposed as choices so the help colorizer highlights them like click.Choice values: the keyword collector duck-types on this attribute (see the getattr(param.type, "choices", ...) branch in _HelpColorsMixin._collect_params). It is also the single source of truth reused by get_metavar() and convert(), so the metavar and the parser never drift apart.

get_metavar(param, ctx=None)[source]

Render [auto|max|INTEGER] (brackets included, as Choice does).

convert(value, param, ctx)[source]

Resolve a keyword to a logical-core count, else parse as an integer.

An already-resolved integer is returned untouched, so option defaults and re-validation can flow back through conversion unharmed. When a parallel-intent keyword (auto/max) resolves to a single job, a warning is logged: the request reads as “use several cores”, but the host has too few logical CPUs, so execution is silently sequential.

Return type:

int

shell_complete(ctx, param, incomplete)[source]

Suggest the auto/max keywords; an integer count is free-form.

Completion proposes only the symbolic keywords, matched case-insensitively to mirror how convert() lower-cases its input. An integer has no finite set to enumerate, so none is offered, yet convert() still accepts one.

Return type:

list[CompletionItem]

class click_extra.execution.JobsOption(param_decls=None, default='auto', expose_value=False, show_default=True, type=<click_extra.execution.JobCount object>, help="Number of parallel jobs. Accepts an integer, 'auto' (one fewer than the host's logical CPUs) or 'max' (all logical CPUs). 0 runs sequentially.", **kwargs)[source]

Bases: ExtraOption

A pre-configured --jobs option to control parallel execution.

Accepts an integer or one of two keywords resolved by JobCount: auto (the default: one fewer than the available logical CPU cores, leaving a core free for the main process and system tasks) and max (every available logical CPU core). A value of 0 disables parallelism and runs sequentially.

The core count is the number of logical CPUs (hardware threads) reported by os.cpu_count(), not physical cores: see CPU_COUNT. On a host with too few logical CPUs, auto/max resolve to a single job and JobCount logs a warning that execution will be sequential.

The resolved value is stored as an int in ctx.meta[click_extra.context.JOBS].

Warning

JobsOption only resolves and publishes the job count: it does not drive any concurrency by itself. Pass it to run_jobs() (which reads the resolved ctx.meta[click_extra.context.JOBS] count), or read that value yourself and act on it.

validate_jobs(ctx, param, value)[source]

Validate the resolved job count and store it in context metadata.

JobCount has already resolved any auto/max keyword to an integer by the time this runs. A value of 0 disables parallelism: it is rounded up to 1 (sequential execution) with a warning. Negative values are likewise clamped to 1, and a count above the available cores is honored but warned about. The resolved count is then logged at info level next to the host’s logical CPU count (CPU_COUNT), so a CLI’s parallelism is visible under --verbosity INFO.

Return type:

None

click_extra.execution.run_jobs(func, items, *, jobs=None)[source]

Run func over items, parallelized per the resolved --jobs count.

The worker count is taken from jobs when given, else from the active command’s JobsOption value (ctx.meta[click_extra.context.JOBS]), else 1. With a single worker (or at most one item) the items run sequentially and lazily, so a caller can stop early on the first result (for example to abort on the first failure); otherwise they run in a thread pool. Either way results are yielded in submission order, like map().

The pool is thread-based, which suits the I/O- and subprocess-bound work CLI tools usually parallelize (each child releases the GIL). The count is a number of logical CPUs: see CPU_COUNT.

Parameters:
  • func (Callable[[TypeVar(T)], TypeVar(R)]) – Called once per item; its return value is yielded.

  • items (Iterable[TypeVar(T)]) – The work items. Materialized up front to size the pool.

  • jobs (int | None) – Override the worker count instead of reading it from the context. 1 or fewer forces sequential execution.

Return type:

Iterator[TypeVar(R)]

Returns:

An iterator over func’s results, in the order of items.

class click_extra.execution.TimerOption(param_decls=None, default=False, expose_value=False, is_eager=True, help='Measure and print elapsed execution time.', **kwargs)[source]

Bases: ExtraOption

A pre-configured option that is adding a --time/--no-time flag to print elapsed time at the end of CLI execution.

The start time is made available in the context in ctx.meta[click_extra.context.START_TIME].

print_timer()[source]

Compute and print elapsed execution time.

Always prints, even when a sibling eager option (--version, --show-params, --show-config…) short-circuited the command body via ctx.exit(). That makes --time a usable probe for the cost of Click Extra’s own machinery (option parsing, config loading, eager callbacks), not just user command bodies.

Return type:

None

init_timer(ctx, param, value)[source]

Set up the execution-timer machinery for the current invocation.

Captures time.perf_counter() as the start time, stores it on ctx.meta under click_extra.context.START_TIME, and queues print_timer() as a context-close callback so the elapsed duration is printed even when a sibling eager option (--version, --show-params…) short-circuits the command body.

Renamed from register_timer_on_close to align with the init_<system> convention shared with init_formatter and init_sort.

Return type:

None

class click_extra.execution.ZeroExitOption(param_decls=None, default=False, expose_value=False, is_flag=True, help='Always exit with a status code of 0, even when problems are found.', **kwargs)[source]

Bases: ExtraOption

A pre-configured -0/--zero-exit option flag.

Follows the convention popularized by linters and static analysers, which exit with a non-zero code whenever they report findings so that automation can gate on it. Setting this flag flips that behavior: the CLI returns 0 as long as it ran to completion, reserving non-zero codes for actual execution failures.

The resolved value is stored in ctx.meta[click_extra.context.ZERO_EXIT], aligning with every other Click Extra option’s per-invocation context-meta storage pattern.

Warning

This option is a placeholder: it does not alter the CLI’s exit code by itself. Downstream code must read ctx.meta[click_extra.context.ZERO_EXIT] and act on it.

set_zero_exit(ctx, param, value)[source]

Store the resolved zero-exit flag on the context’s meta dict.

Read via click_extra.context.get(ctx, click_extra.context.ZERO_EXIT).

Return type:

None

click_extra.highlight module

Help-screen keyword highlighting and the colorized help formatter.

Hosts the engine that collects highlightable keywords from a Click context (HelpKeywords, _HelpColorsMixin) and renders them with the active theme: HelpFormatter styles --help output and highlight() applies a styling function to arbitrary matches. Split out of click_extra.color, which now focuses on --color/--no-color resolution.

class click_extra.highlight.HelpKeywords(cli_names=<factory>, subcommands=<factory>, command_aliases=<factory>, arguments=<factory>, long_options=<factory>, short_options=<factory>, choices=<factory>, choice_metavars=<factory>, metavars=<factory>, envvars=<factory>, defaults=<factory>)[source]

Bases: object

Structured collection of keywords extracted from a Click context for help screen highlighting.

Each field corresponds to a semantic category with its own styling.

cli_names: set[str]
subcommands: set[str]
command_aliases: set[str]
arguments: set[str]
long_options: set[str]
short_options: set[str]
choices: set[str]
choice_metavars: set[str]
metavars: set[str]
envvars: set[str]
defaults: set[str]
merge(other)[source]

Merge another HelpKeywords into this one.

Each set field is updated with the corresponding set from other.

Return type:

None

subtract(other)[source]

Remove keywords found in other from this instance.

Each set field is difference-updated with the corresponding set from other. Mirror of merge().

Return type:

None

class click_extra.highlight.HelpFormatter(*args, **kwargs)[source]

Bases: HelpFormatter

Extends Cloup’s custom HelpFormatter to highlights options, choices, metavars and default values.

This is being discussed for upstream integration at:

Forces theme to the active one for the current Click context.

Also transform Cloup’s standard HelpTheme to our own HelpTheme.

Resolves the active theme via click_extra.theme.get_current_theme(), which reads the per-invocation pick from the Click context (set by ThemeOption) and falls back to the module-level default when no context is active.

theme: HelpTheme
write_usage(prog, args='', prefix=None)[source]

ANSI-aware override of cloup.HelpFormatter.write_usage.

On Click 8.3.x, click.formatting.wrap_text measures line length with raw len(), counting every byte of the ANSI escape sequences embedded in initial_indent (the styled Usage: heading + invoked-command name). With 24-bit RGB themes (like Solarized Dark, Dracula, Nord, Monokai), each styled token carries 17+ extra bytes of escape, which inflates the measured line beyond the width budget and causes premature wraps mid-token: [OPTIONS\n  ].

Cloup styles prefix and prog then delegates to click’s HelpFormatter.write_usage(), inheriting the bug. This override re-applies the same styling, then bypasses wrap_text whenever the visible content fits on a single line: the common case for short usage strings where wrapping is unnecessary. Lines that genuinely overflow the visible width fall back to click’s implementation: the wrap point may still be sub-optimal but the output stays syntactically valid.

Note

Click 8.4.0 (PR pallets/click#3420) made click.formatting.TextWrapper ANSI-aware by counting visible width instead of raw bytes, so this override is a no-op fast path on Click >= 8.4.0 and only fixes wrapping on the Click 8.3.x releases click-extra still supports.

Todo

Drop this override once the minimum supported Click rises to 8.4.0 (which includes pallets/click#3420). The term_len-based visible-width check below becomes redundant once Click’s own wrapper counts visible width.

Return type:

None

keywords: HelpKeywords = HelpKeywords(cli_names=set(), subcommands=set(), command_aliases=set(), arguments=set(), long_options=set(), short_options=set(), choices=set(), choice_metavars=set(), metavars=set(), envvars=set(), defaults=set())
excluded_keywords: HelpKeywords | None = None
highlight_extra_keywords(help_text)[source]

Highlight extra keywords in help screens based on the theme.

Uses the highlight() function for all keyword categories. Each category is processed as a batch of regex patterns with a single styling function, which handles overlapping matches and prevents double-styling.

Return type:

str

getvalue()[source]

Wrap original Click.HelpFormatter.getvalue() to force extra-colorization on rendering.

Return type:

str

click_extra.highlight.highlight(content, patterns, styling_func, ignore_case=False)[source]

Highlights parts of the content that matches patterns.

Takes care of overlapping parts within the content, so that the styling function is applied only once to each contiguous range of matching characters.

Todo

Support case-foldeing, so we can have the Straße string matching the Strasse content.

This could be tricky as it messes with string length and characters index, which our logic relies on.

Danger

Roundtrip through lower-casing/upper-casing is a can of worms, because some characters change length when their case is changed:

Return type:

str

click_extra.logging module

Logging utilities.

class click_extra.logging.LogLevel(*values)[source]

Bases: IntEnum

Mapping of canonical log level names to their integer level.

That’s our own version of logging._nameToLevel, but:

CRITICAL = 50
ERROR = 40
WARNING = 30
INFO = 20
DEBUG = 10
click_extra.logging.DEFAULT_LEVEL: LogLevel = LogLevel.WARNING

WARNING is the default level we expect any loggers to starts their lives at.

WARNING has been chosen as it is the level at which the default Python’s global root logger is set up.

This value is also used as the default level for VerbosityOption .

class click_extra.logging.StreamHandler(stream=None)[source]

Bases: StreamHandler

A handler to output logs to the console.

Wraps logging.StreamHandler, but use click.echo() to support color printing.

Only <stderr> or <stdout> are allowed as output stream.

If stream is not specified, <stderr> is used by default

Initialize the handler.

If stream is not specified, sys.stderr is used.

property stream: IO[Any]

The stream to which logs are written.

A proxy of the parent logging.StreamHandler’s stream attribute.

Redefined here to enforce checks on the stream value.

emit(record)[source]

Use click.echo() to print to the console.

Return type:

None

class click_extra.logging.Formatter(fmt=None, datefmt=None, style='%', validate=True, *, defaults=None)[source]

Bases: Formatter

Click Extra’s default log formatter.

Initialize the formatter with specified format strings.

Initialize the formatter either with the specified format string, or a default as described above. Allow for specialized date formatting with the optional datefmt argument. If datefmt is omitted, you get an ISO8601-like (or RFC 3339-like) format.

Use a style parameter of ‘%’, ‘{’ or ‘$’ to specify that you want to use one of %-formatting, str.format() ({}) formatting or string.Template formatting in your format string.

Changed in version 3.2: Added the style parameter.

formatMessage(record)[source]

Colorize the record’s log level name before calling the standard formatter.

Colors are sourced from a click_extra.theme.HelpTheme, resolved per-invocation via click_extra.theme.get_current_theme().

Return type:

str

click_extra.logging.basicConfig(*, filename=None, filemode='a', format='{levelname}: {message}', datefmt=None, style='{', level=None, stream=None, handlers=None, force=False, encoding=None, errors='backslashreplace', stream_handler_class=<class 'click_extra.logging.StreamHandler'>, file_handler_class=<class 'logging.FileHandler'>, formatter_class=<class 'click_extra.logging.Formatter'>)[source]

Configure the global root logger.

This function is a wrapper around Python standard library’s logging.basicConfig(), but with additional parameters and tweaked defaults.

It sets up the global root logger, and optionally adds a file or stream handler to it.

Differences in default values:

Argument

basicConfig() default

logging.basicConfig() default

style

{

%

format

{levelname}: {message}

%(levelname)s:%(name)s:%(message)s

This function takes the same parameters as logging.basicConfig(), but require them to be all passed as explicit keywords arguments.

Parameters:
  • filename (str | None) – Specifies that a logging.FileHandler be created, using the specified filename, rather than an StreamHandler.

  • filemode (str) –

    If filename is specified, open the file in this mode.

    Defaults to a.

  • format (str | None) –

    Use the specified format string for the handler.

    Defaults to {levelname}: {message}.

  • datefmt (str | None) – Use the specified date/time format, as accepted by time.strftime().

  • style (Literal['%', '{', '$']) –

    If format is specified, use this style for the format string:

    Defaults to {.

  • level (int | str | None) – Set the root logger level to the specified level.

  • stream (IO[Any] | None) – Use the specified stream to initialize the StreamHandler. Note that this argument is incompatible with filename - if both are present, a ValueError is raised.

  • handlers (Iterable[Handler] | None) – If specified, this should be an iterable of already created handlers to add to the root logger. Any handlers which don’t already have a formatter set will be assigned the default formatter created in this function. Note that this argument is incompatible with filename or stream - if both are present, a ValueError is raised.

  • force (bool) – If this argument is specified as True, any existing handlers attached to the root logger are removed and closed, before carrying out the configuration as specified by the other arguments.

  • encoding (str | None) – Name of the encoding used to decode or encode the file. To be specified along with filename, and passed to logging.FileHandler for opening the output file.

  • errors (str | None) – Optional string that specifies how encoding and decoding errors are to be handled by the logging.FileHandler. Defaults to backslashreplace. Note that if None is specified, it will be passed as such to open().

Return type:

None

Important

Always keep the signature of this function, the default values of its parameters and its documentation in sync with the one from Python’s standard library.

These new arguments are available for better configurability:

Parameters:

Note

I don’t like the camel-cased name of this function and would have called it basic_config(), but it’s kept this way for consistency with Python’s standard library logging.basicConfig().

click_extra.logging.new_logger(name='root', *, propagate=False, force=True, **kwargs)[source]

Setup a logger in the style of Click Extra.

By default, this helper will:

  • Fetch the logger registered under the name parameter, or creates a new one with that name if it doesn’t exist,

  • Set the logger’s propagate attribute to False,

  • Force removal of any existing handlers and formatters attached to the logger,

  • Attach a new StreamHandler with Formatter,

  • Return the logger object.

This function is a wrapper around basicConfig() and takes the same keywords arguments.

Parameters:
  • name (str) – ID of the logger to setup. If None, Python’s root logger will be used. If a logger with the provided name is not found in the global registry, a new logger with that name will be created.

  • propagate (bool) – Sets the logger’s propagate attribute. Defaults to False.

  • force (bool) – Same as the force parameter from logging.basicConfig() and basicConfig(). Defaults to True.

  • kwargs – Any other keyword parameters supported by logging.basicConfig() and basicConfig().

Return type:

Logger

class click_extra.logging.VerbosityOption(param_decls=None, default_logger='root', default=LogLevel.WARNING, metavar='LEVEL', type=EnumChoice('CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG'), help='Either CRITICAL, ERROR, WARNING, INFO, DEBUG.', **kwargs)[source]

Bases: _VerbosityOption

--verbosity LEVEL option to set the log level of _VerbosityOption.

Set up a verbosity-altering option.

Parameters:

default_logger (Logger | str) – If a logging.Logger object is provided, that’s the instance to which we will set the level to. If the parameter is a string and is found in the global registry, we will use it as the logger’s ID. Otherwise, we will create a new logger with new_logger() Default to the global root logger.

set_level(ctx, param, value)[source]

Record the --verbosity value, then reconcile.

The value passed to --verbosity is saved in ctx.meta[click_extra.context.VERBOSITY].

Return type:

None

class click_extra.logging.VerboseOption(param_decls=None, count=True, **kwargs)[source]

Bases: _VerbosityOption

--verbose/-v option to raise the log level of _VerbosityOption by one step per repetition.

Each -v raises the verbosity by one LogLevel step. The option can be repeated, so -vv (or -v -v) raises it by two steps.

The base level the counter starts from is sourced from VerbosityOption.default. So with --verbosity’s default left at WARNING:

  • -v raises the level to INFO,

  • -vv raises the level to DEBUG,

  • any further repetition is clamped at the loudest level, so -vvvvv for example resolves to DEBUG.

-v shares a single signed counter with QuietOption’s -q, so the two cancel out: -v -q leaves the level unchanged. See _VerbosityOption.resolve_level for the full reconciliation rule with --verbosity.

Set up a verbosity-altering option.

Parameters:

default_logger – If a logging.Logger object is provided, that’s the instance to which we will set the level to. If the parameter is a string and is found in the global registry, we will use it as the logger’s ID. Otherwise, we will create a new logger with new_logger() Default to the global root logger.

set_level(ctx, param, value)[source]

Record the -v repetition count, then reconcile.

The number of repetitions is saved in ctx.meta[click_extra.context.VERBOSE] and folded into the verbosity counter by _VerbosityOption.resolve_level.

Return type:

None

class click_extra.logging.QuietOption(param_decls=None, count=True, **kwargs)[source]

Bases: _VerbosityOption

--quiet/-q option to lower the log level of _VerbosityOption by one step per repetition.

The symmetric counterpart of VerboseOption: where -v raises the verbosity one LogLevel step at a time, -q lowers it. Starting from VerbosityOption.default (WARNING by default):

  • -q lowers the level to ERROR,

  • -qq lowers the level to CRITICAL,

  • any further repetition is clamped at the quietest level, so -qqqqq for example resolves to CRITICAL.

-q shares a single signed counter with VerboseOption’s -v, so the two cancel out: -v -q leaves the level unchanged. See _VerbosityOption.resolve_level for the full reconciliation rule with --verbosity.

Set up a verbosity-altering option.

Parameters:

default_logger – If a logging.Logger object is provided, that’s the instance to which we will set the level to. If the parameter is a string and is found in the global registry, we will use it as the logger’s ID. Otherwise, we will create a new logger with new_logger() Default to the global root logger.

set_level(ctx, param, value)[source]

Record the -q repetition count, then reconcile.

The number of repetitions is saved in ctx.meta[click_extra.context.QUIET] and folded into the verbosity counter by _VerbosityOption.resolve_level.

Return type:

None

click_extra.parameters module

Our own flavor of Option, Argument and parameters.

class click_extra.parameters.P

Type variable bound to click.Parameter, letting require_sibling_param() return the exact subclass it was asked to find.

alias of TypeVar(‘P’, bound=Parameter)

click_extra.parameters.PARAM_PATH_SEP = '.'

Separator joining the keys of a parameter’s fully-qualified path (cli.subcommand.param).

click_extra.parameters.patch_attr(obj, name, value)[source]

Temporarily set obj.name to value, restoring the original on exit.

A minimal, dependency-free stand-in for unittest.mock.patch.object for the simple save-set-restore monkeypatching Click Extra performs at runtime (in logging, parameters and testing).

Note

unittest.mock drags the whole test framework, and its heavy transitive imports, into the startup path of every CLI built with Click Extra. Reimplementing the single feature actually used keeps that cost out of import time. Do not swap this back for unittest.mock.

Like patch.object without create=True, the attribute must already exist: a missing name raises AttributeError.

Return type:

Iterator[None]

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

Search a particular class of parameter in a list and return them.

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

  • klass (type[Parameter]) – the class of the parameters to look for.

  • include_subclasses (bool) – if True, includes in the results all parameters subclassing the provided klass. If False, only matches parameters which are strictly instances of klass. Defaults to True.

  • unique (bool) – if True, raise an error if more than one parameter of the provided klass is found. Defaults to True.

Return type:

list[Parameter] | Parameter | None

click_extra.parameters.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:
Return type:

Parameter | None

click_extra.parameters.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[TypeVar(P, bound= Parameter)]) – the sibling parameter class to look for.

Return type:

TypeVar(P, bound= Parameter)

class click_extra.parameters.Argument(*args, help=None, **attrs)[source]

Bases: _ParameterMixin, Argument

Wrap cloup.Argument, itself inheriting from click.Argument.

Inherits first from _ParameterMixin to allow future overrides of Click’s Parameter methods.

class click_extra.parameters.Option(*args, group=None, **attrs)[source]

Bases: _ParameterMixin, Option

Wrap cloup.Option, itself inheriting from click.Option.

Inherits first from _ParameterMixin to allow future overrides of Click’s Parameter methods.

class click_extra.parameters.ExtraOption(*args, group=None, **attrs)[source]

Bases: Option

Dedicated to option implemented by click-extra itself.

Provides a way to identify Click Extra’s own options with certainty, and restores the pre-Click-8.4.0 contract that eager callbacks can introspect their own parameter source from within their own callback.

Note

This is the one click-extra class that deliberately keeps the Extra prefix. The 8.0.0 cleanup dropped it everywhere else (ExtraCommand became Command, ExtraContext became Context, and so on), shadowing the matching Cloup or Click class. Here the plain Option name is already taken by the user-facing enhanced wrapper this class subclasses, so the prefix is not legacy baggage but a real distinction: ExtraOption marks click-extra’s own built-in options. That marker is load-bearing, since Command sorts parameters with isinstance(param, ExtraOption) to push the built-in options to the end.

Note

Bracket fields (envvar, default, range, required) cannot be pre-styled in get_help_record() because Click’s text wrapper splits lines after the record is returned, which would break ANSI codes that span wrapped boundaries. Styling is instead applied post-wrapping in HelpFormatter._style_bracket_fields(), which uses the structured data from Option.get_help_extra() to identify each field by its label.

Note

Built-in option subclasses share a common shape: their __init__ defaults param_decls to the option’s canonical flags and wires an eager callback via kwargs.setdefault("callback", self.<callback>). Every callback name encodes its role with a verb prefix. The common roles are:

  • set_<key> publishes a resolved value to ctx.meta (set_color, set_no_color, set_theme, set_telemetry, set_progress, set_accessible, set_zero_exit, the verbosity options’ set_level);

  • init_<system> additionally installs a ctx helper or records a snapshot (init_timer, init_formatter, init_columns, init_sort);

  • validate_<thing> coerces and validates the raw input (validate_jobs, validate_config);

  • print_* renders output and exits (print_man, print_params, print_and_exit).

A few options own a richer operation and name it with its own verb rather than forcing one of the above. ConfigOption wires load_conf to read, parse, and merge a configuration file, and NoConfigOption wires check_sibling_config_option to assert that a sibling --config option exists.

handle_parse_result(ctx, opts, args)[source]

Record the parameter source before delegating to the base implementation.

Warning

Click 8.4.0 (PR pallets/click#3404) reordered Parameter.handle_parse_result so ctx.set_parameter_source runs after process_value. Eager callbacks that introspect their own provenance via ctx.get_parameter_source(self.name) therefore read None instead of the actual source. ColorOption, ConfigOption, and ShowParamsOption all rely on this introspection to decide whether an env var should override the default (--color), whether the --config path was user-supplied, and what to render in the Source column of --show-params.

Click 8.4.1 restored the pre-8.4.0 contract upstream (PR pallets/click#3484), so this override only matters for Click 8.4.0 itself, which sits inside click-extra’s supported >= 8.3.1 range. Pre-recording the source here for eager options keeps that contract on every supported Click. super().handle_parse_result re-records the same value at the canonical time, so the slot arbitration logic introduced by #3404 is unaffected: slot_empty is computed from ctx.params, not from _parameter_source.

consume_value runs twice as a side effect: once here and once in super. Both calls are pure for click-extra’s existing eager flag-style options (no env var side effects, no prompt). Should a future eager subclass need prompt behavior, this override would need to cache the result instead.

The pre-record is skipped when the slot already carries a source from an earlier option sharing the same name (Click’s feature-switch pattern), so the arbitration logic in super still sees the original existing_source rather than a stale rewrite from this option.

class click_extra.parameters.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.

included_params: frozenset[str] | None

Allowlist of parameter IDs, mutually exclusive with excluded_params.

None disables the allowlist. It is resolved into excluded_params by build_param_trees(), once every parameter ID is known.

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

Utility method to recursively create a nested dict structure whose keys are provided by path list and at the end is populated by a copy of leaf.

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()[source]

Generate an unfiltered list of all CLI parameters.

Everything is included, from top-level groups to subcommands, and from options to arguments.

Return type:

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

Yields a 2-element tuple:
  • a tuple of keys leading to the parameter;

  • the parameter object itself.

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

See the list of custom types provided by Click.

Return type:

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

build_param_trees()[source]

Build the parameters tree structure and cache it.

This removes parameters whose fully-qualified IDs are in the excluded_params blocklist.

If included_params was provided, it is resolved into excluded_params here, where all parameter IDs are available.

Return type:

None

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.parameters.get_param_spec(param, ctx)[source]

Extract the option-spec string (like -v, --verbose) from a parameter.

Temporarily unhides hidden options so their help record can be produced.

Note

The hidden property is only supported by Option, not Argument.

Todo

Submit a PR to Click to separate production of param spec and help record. That way we can always produce the param spec even if the parameter is hidden. See: https://github.com/kdeldycke/click-extra/issues/689

Return type:

str | None

click_extra.parameters.format_param_row(param, ctx, path, is_structured)[source]

Compute the structural table cells for a Click parameter.

Returns a dict[column_id, cell] covering every column that can be derived from the parameter object alone (no runtime invocation state or config-file context). Specifically: id, spec, class, param_type, python_type, hidden, exposed, envvars, default, is_flag, flag_value, is_bool_flag, multiple, nargs, prompt, and confirmation_prompt.

Attributes only defined on click.Option (hidden, is_flag, flag_value, is_bool_flag, prompt, confirmation_prompt) yield None for click.Argument parameters: empty cell in visual formats, null in structured ones.

For structured formats (JSON, YAML, etc.), values are native Python types. For visual formats, values are themed strings matching help-screen styling.

The remaining table columns (allowed_in_conf, value, source) require live context and are filled in by render_params_table().

Return type:

dict[str, Any]

click_extra.parameters.walk_command_params(cmd, ctx, parent_keys=())[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, so context-sensitive metadata (notably the auto-generated environment variable, which derives from Context.auto_envvar_prefix) is computed at the correct nesting level 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.

Return type:

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

click_extra.parameters.render_params_table(subject_ctx, *, default_columns=None)[source]

Introspect subject_ctx.command and print its parameter metadata table.

Walks the command and any nested subcommands, emitting one row per parameter. The table format and column selection are read from subject_ctx.meta (see TABLE_FORMAT and COLUMNS); when neither is set, a sibling --table-format / --columns option on the command is consulted, then the default_columns fallback, then the canonical order.

When subject_ctx.meta carries pre-parsed RAW_ARGS, the value and source columns are resolved by replaying those arguments against the command parser; otherwise they fall back to the parameter defaults.

This is the shared rendering core behind both print_params() (introspecting the live CLI) and the click-extra wrap --show-params path (introspecting a foreign target). The caller is responsible for exiting the context afterwards.

Important

Click does not keep the raw, pre-parsed arguments around, so values and their provenance cannot be read back directly. The workaround replays RAW_ARGS (captured on the context by Command/Group) through the command parser, calling consume_value() rather than handle_parse_result() so eager callbacks are not re-triggered.

Return type:

None

class click_extra.parameters.ShowParamsOption(param_decls=None, is_flag=True, expose_value=False, is_eager=True, help='Show all CLI parameters, their provenance, defaults and value, then exit.', **kwargs)[source]

Bases: ExtraOption, ParamStructure

A pre-configured option adding a --show-params option.

Between configuration files, default values and environment variables, it might be hard to guess under which set of parameters the CLI will be executed. This option print information about the parameters that will be fed to the CLI.

TABLE_HEADERS: ClassVar[tuple[_ColumnSpec, ...]] = (ColumnSpec(id='id', label='ID', description='Fully-qualified parameter path (`cli.subcommand.param-name`) derived from the [`click.Command`](https://click.palletsprojects.com/en/stable/api/#click.Command) tree. Doubles as the key used to address the parameter from a configuration file.'), ColumnSpec(id='spec', label='Spec.', description='Option/argument specification string (like `-v, --verbose`) extracted from [`click.Parameter.get_help_record()`](https://click.palletsprojects.com/en/stable/api/#click.Parameter).'), ColumnSpec(id='class', label='Class', description="Fully-qualified class of the parameter: a subclass of [`click.Option`](https://click.palletsprojects.com/en/stable/api/#click.Option), [`click.Argument`](https://click.palletsprojects.com/en/stable/api/#click.Argument), [`cloup.Option`](https://cloup.readthedocs.io/en/stable/autoapi/cloup/index.html#cloup.Option), or one of Click Extra's own wrappers ([`click_extra.parameters.Option`](#click_extra.parameters.Option), [`click_extra.parameters.Argument`](#click_extra.parameters.Argument), [`click_extra.parameters.ExtraOption`](#click_extra.parameters.ExtraOption))."), ColumnSpec(id='param_type', label='Param type', description='Click value converter class: a subclass of [`click.ParamType`](https://click.palletsprojects.com/en/stable/api/#click.ParamType) like [`click.IntRange`](https://click.palletsprojects.com/en/stable/api/#click.IntRange), [`click.Choice`](https://click.palletsprojects.com/en/stable/api/#click.Choice), or a Click Extra type.'), ColumnSpec(id='python_type', label='Python type', description='Python built-in type the parsed value resolves to: [`str`](https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str), [`int`](https://docs.python.org/3/library/functions.html#int), [`float`](https://docs.python.org/3/library/functions.html#float), [`bool`](https://docs.python.org/3/library/functions.html#bool), or [`list`](https://docs.python.org/3/library/stdtypes.html#list). Computed by [`ParamStructure.get_param_type()`](#click_extra.parameters.ParamStructure.get_param_type) from the Click `Param type`.'), ColumnSpec(id='hidden', label='Hidden', description="Reflects [`click.Option`'s `hidden`](https://click.palletsprojects.com/en/stable/api/#click.Option) constructor argument: the option is omitted from `--help` output. Empty for [`click.Argument`](https://click.palletsprojects.com/en/stable/api/#click.Argument), which does not support hiding."), ColumnSpec(id='exposed', label='Exposed', description="Reflects [`click.Parameter`'s `expose_value`](https://click.palletsprojects.com/en/stable/api/#click.Parameter) constructor argument: whether the parsed value is forwarded to the command callback. Eager options like `--show-params` and `--help` typically run a callback and exit, so they are not exposed."), ColumnSpec(id='allowed_in_conf', label='Allowed in conf?', description='Click Extra-specific: whether the parameter is reachable from a configuration file. Controlled by [`ParamStructure.excluded_params`](#click_extra.parameters.ParamStructure.excluded_params) and [`included_params`](#click_extra.parameters.ParamStructure.included_params). Empty when the CLI has no [`--config` option](config.md).'), ColumnSpec(id='envvars', label='Env. vars.', description="Environment variables read for this parameter: the explicit [`click.Parameter`'s `envvar`](https://click.palletsprojects.com/en/stable/api/#click.Parameter) plus the auto-resolved IDs documented in [Environment variables](envvar.md)."), ColumnSpec(id='default', label='Default', description='Default value returned by [`click.Parameter.get_default()`](https://click.palletsprojects.com/en/stable/api/#click.Parameter.get_default), rendered as its Python `repr()`.'), ColumnSpec(id='is_flag', label='Is flag', description="Reflects [`click.Option`'s `is_flag`](https://click.palletsprojects.com/en/stable/api/#click.Option): whether the option behaves as a flag (no value taken from the command line). Empty for [`click.Argument`](https://click.palletsprojects.com/en/stable/api/#click.Argument)."), ColumnSpec(id='flag_value', label='Flag value', description="Reflects [`click.Option`'s `flag_value`](https://click.palletsprojects.com/en/stable/api/#click.Option): the Python value substituted for the option when its flag is used. Defaults to `True` for boolean flags, can be any value for flag-value style options (like `@option('--upper', 'transform', flag_value='upper')`)."), ColumnSpec(id='is_bool_flag', label='Is bool flag', description='Reflects `click.Option.is_bool_flag` (set internally by Click when `flag_value` is `True` or `False`): the option is a *true* boolean flag, as opposed to a flag-value style option.'), ColumnSpec(id='multiple', label='Multiple', description="Reflects [`click.Parameter`'s `multiple`](https://click.palletsprojects.com/en/stable/api/#click.Parameter): the parameter can be repeated on the command line, collecting values into a tuple."), ColumnSpec(id='nargs', label='Nargs', description="Reflects [`click.Parameter`'s `nargs`](https://click.palletsprojects.com/en/stable/api/#click.Parameter): the number of CLI tokens the parameter consumes. `1` is the default; `-1` denotes a variadic argument."), ColumnSpec(id='prompt', label='Prompt', description="Reflects [`click.Option`'s `prompt`](https://click.palletsprojects.com/en/stable/api/#click.Option): the text shown to the user when the option is not provided on the command line. Empty when no prompt is configured."), ColumnSpec(id='confirmation_prompt', label='Confirmation prompt', description="Reflects [`click.Option`'s `confirmation_prompt`](https://click.palletsprojects.com/en/stable/api/#click.Option): whether the user is asked to enter the value twice for confirmation."), ColumnSpec(id='value', label='Value', description='Current value of the parameter at invocation time, computed by [`click.Parameter.consume_value()`](https://click.palletsprojects.com/en/stable/api/#click.Parameter) from the merged sources (CLI, environment, config file, default).'), ColumnSpec(id='source', label='Source', description='Provenance of the resolved value: a [`click.core.ParameterSource`](https://click.palletsprojects.com/en/stable/api/#click.core.ParameterSource) enum member such as `COMMANDLINE`, `ENVIRONMENT`, `DEFAULT_MAP`, or `DEFAULT`.'))

Rich column registry for the --show-params table.

Each entry is a click_extra.table.ColumnSpec carrying the column’s stable id (used by --columns and as structured-format key), its display label, and a MyST/Markdown description consumed by the documentation’s auto-generated Available columns section. Iteration yields columns in canonical display order.

classmethod column_labels()[source]

Return just the display labels of TABLE_HEADERS (in order).

Return type:

tuple[str, ...]

classmethod column_ids()[source]

Return just the stable IDs of TABLE_HEADERS (in order).

Return type:

tuple[str, ...]

classmethod find_column(column_id)[source]

Return the ColumnSpec matching column_id.

Raises KeyError if no column has this ID; callers should convert the error into a click.UsageError when surfaced to a user.

classmethod render_doc_table()[source]

Render TABLE_HEADERS as a Markdown table for documentation.

Used by the show_params_columns_table MyST substitution in docs/conf.py to feed the Available columns section of docs/parameters.md: editing a description here automatically rebuilds the docs table on the next sphinx-build.

Return type:

str

excluded_params

Deactivates the blocking of any parameter.

included_params

No allowlist filter; show all parameters.

print_params(ctx, param, value)[source]

Introspect the current CLI and print its parameter metadata table.

Thin wrapper over render_params_table(), the shared rendering core also driving click-extra wrap --show-params for foreign CLIs. The live invocation context carries everything the core needs: the captured RAW_ARGS (attached by Command/Group) for value and source resolution, plus any sibling --table-format / --columns options.

Return type:

None

click_extra.prebake module

Bake build-time metadata into Python source files before compilation.

Compiled binaries (Nuitka, PyInstaller) and git-less runtimes (Docker images, archive checkouts) cannot resolve version or Git metadata at runtime the way click_extra.version.VersionOption does. The values must instead be written into the source before the build, by rewriting the relevant dunder assignments (__version__, __git_short_hash__, …) in place with ast.

This mirrors shadow-rs, which injects build-time constants (BRANCH, SHORT_COMMIT, COMMIT_HASH, COMMIT_DATE, TAG, …) into Rust binaries at compile time.

Todo

Add the following build-time template fields, mirroring the constants shadow-rs injects:

  • {build_time}: when the distribution was built (shadow-rs exposes it as BUILD_TIME, with RFC 2822 and RFC 3339 variants BUILD_TIME_2822 / BUILD_TIME_3339).

  • {build_os} / {build_target} / {build_target_arch}: the OS, target triple and architecture the build ran on. These describe the build host, unlike {env_info} which reports the runtime Python, OS and architecture, so both are worth keeping for cross-built binaries.

click_extra.prebake.prebake_version(file_path, local_version)[source]

Pre-bake a __version__ string with a PEP 440 local version identifier.

Reads file_path, finds the __version__ assignment via ast, and, if the version contains .dev and does not already contain +, appends +<local_version>.

This is the compile-time complement to the runtime click_extra.version.VersionOption.version property: Nuitka/PyInstaller binaries cannot run git at runtime, so the hash must be baked into __version__ in the source file before compilation.

Returns the new version string on success, or None if no change was made (release version, already pre-baked, or no __version__ found).

Return type:

str | None

click_extra.prebake.prebake_dunder(file_path, name, value)[source]

Replace an empty dunder variable’s value in a Python source file.

Reads file_path, finds a top-level name = "" assignment via ast, and, if the current value is an empty string, replaces it with value.

Placeholders must use empty strings (__field__ = "", not None). The AST matcher only recognizes string literals, and the empty string acts as a falsy sentinel that stays type-consistent with baked values (always str).

This is the generic counterpart to prebake_version(): where prebake_version appends a PEP 440 local identifier to __version__, this function does a full replacement of any dunder variable that starts empty. Typical use case: injecting a release commit SHA into __git_tag_sha__ = "" at build time.

Returns the new value on success, or None if no change was made (variable not found, or already has a non-empty value).

Return type:

str | None

click_extra.prebake.discover_package_init_files()[source]

Discover __init__.py files from [project.scripts].

Reads the pyproject.toml in the current working directory, extracts [project.scripts] entry points, and returns the unique __init__.py paths for each top-level package.

Only returns paths that exist on disk. Returns an empty list if pyproject.toml is missing or has no [project.scripts].

Return type:

list[Path]

click_extra.pygments module

Pygments lexers, filters, and formatters for ANSI escape sequences.

Parses ANSI SGR escape sequences (ECMA-48 / ISO 6429) from terminal output and renders them as colored HTML with CSS classes. Supports the standard 8/16 named colors, the 256-color indexed palette, and 24-bit RGB.

SGR text attributes: bold, faint, italic, underline, blink, reverse video, strikethrough, and overline.

OSC 8 hyperlinks are rendered as HTML <a> tags. Other OSC sequences are silently stripped.

Note

24-bit RGB colors (SGR 38;2;r;g;b and 48;2;r;g;b) are preserved by default and rendered by AnsiHtmlFormatter as inline style="color: #rrggbb" / style="background-color: #rrggbb" spans (CSS classes cannot enumerate 16.7M colors). Other token components (bold, named colors, palette indices) keep their CSS-class rendering. Pass true_color=False to AnsiColorLexer, AnsiFilter, or any session lexer (via get_lexer_by_name(..., true_color=False)) to opt into quantization to the nearest entry in the 256-color palette instead.

click_extra.pygments.Ansi = ('Ansi',)

Unified token namespace for ANSI styling.

Compound tokens from the lexer (like Token.Ansi.Bold.Red) and individual style components (like Token.Ansi.Red) share this single namespace. The formatter decomposes compound tokens into individual CSS classes at render time.

click_extra.pygments.DEFAULT_TOKEN_TYPE = ('Generic', 'Output')

Default Pygments token type to render with ANSI support.

Defaults to Generic.Output tokens, as this is the token type used by all REPL-like and terminal session lexers.

class click_extra.pygments.AnsiColorLexer(*args, **kwargs)[source]

Bases: Lexer

Lexer for text containing ANSI escape sequences.

Parses Select Graphic Rendition (SGR) codes and emits compound Token.Ansi.* tokens representing the active styling state. OSC 8 hyperlinks emit Token.AnsiLinkStart / Token.AnsiLinkEnd structural tokens. All other escape sequences are silently stripped.

Supported SGR codes:

  • Text attributes: bold (1), faint (2), italic (3), underline (4), blink (5), reverse video (7), strikethrough (9), overline (53), and their resets.

  • Named colors: standard (30-37, 40-47) and bright (90-97, 100-107).

  • 256-color indexed palette (38;5;n, 48;5;n).

  • 24-bit RGB (38;2;r;g;b, 48;2;r;g;b), quantized to the nearest 256-color entry.

Supported OSC sequences:

  • OSC 8 hyperlinks: rendered as <a> tags by AnsiHtmlFormatter. Only URLs with safe schemes (http, https, mailto, ftp, ftps) are emitted; others are stripped.

Initialize the lexer.

Parameters:

true_color – Default True. 24-bit RGB sequences are preserved as Token.Ansi.FG_{rrggbb} / Token.Ansi.BG_{rrggbb} tokens, which AnsiHtmlFormatter renders as inline style="color: #rrggbb" / style="background-color: #rrggbb" attributes (CSS classes cannot enumerate 16.7M colors). Pass False to quantize 24-bit RGB to the nearest entry in the 256-color palette and emit Token.Ansi.C{n} / Token.Ansi.BGC{n} tokens that map to CSS classes via the style dict.

name = 'ANSI Color'

Full name of the lexer, in human-readable form

aliases = ('ansi-color', 'ansi', 'ansi-terminal')

A list of short, unique identifiers that can be used to look up the lexer from a list, e.g., using get_lexer_by_name().

get_tokens_unprocessed(text)[source]

Parse ANSI escape sequences from text and yield styled tokens.

SGR sequences update the styling state. OSC 8 hyperlinks emit structural Token.AnsiLinkStart / Token.AnsiLinkEnd tokens. All other escape sequences are consumed and stripped.

Return type:

Iterator[tuple[int, _TokenType, str]]

class click_extra.pygments.AnsiFilter(**options)[source]

Bases: Filter

Custom filter transforming a particular kind of token (Generic.Output by default) into ANSI tokens.

Initialize an AnsiColorLexer and configure the token_type to be colorized.

Parameters:

true_color – Forwarded to the inner AnsiColorLexer to control whether 24-bit RGB sequences are preserved as FG_/BG_ hex tokens for inline-style rendering (default True) or quantized to the 256-color palette. See AnsiColorLexer for details.

Note

Only one token_type is supported. All Pygments session lexers (ShellSessionBaseLexer and the manually-maintained list in collect_session_lexers) emit terminal output exclusively as Generic.Output. No upstream issue or PR proposes splitting output into additional token types (like Generic.Error for stderr). If that changes, this filter would need to accept a set of token types instead of a single one. See pygments#1148 and pygments#2499 for the closest related discussions.

filter(lexer, stream)[source]

Transform each token of token_type type into a stream of ANSI tokens.

Return type:

Iterator[tuple[_TokenType, str]]

click_extra.pygments.collect_session_lexers()[source]

Retrieve all lexers producing shell-like sessions in Pygments.

This function contains a manually-maintained list of lexers, to which we dynamically add lexers inheriting from ShellSessionBaseLexer.

Hint

To help maintain this list, there is a test that will fail if a new REPL/terminal-like lexer is added to Pygments but not referenced here.

Return type:

Iterator[type[Lexer]]

click_extra.pygments.LEXER_MAP: dict[type[Lexer], type[Lexer]] = {<class 'pygments.lexers.algebra.GAPConsoleLexer'>: <class 'pygments.lexer.AnsiGAPConsoleLexer'>, <class 'pygments.lexers.dylan.DylanConsoleLexer'>: <class 'pygments.lexer.AnsiDylanConsoleLexer'>, <class 'pygments.lexers.erlang.ElixirConsoleLexer'>: <class 'pygments.lexer.AnsiElixirConsoleLexer'>, <class 'pygments.lexers.erlang.ErlangShellLexer'>: <class 'pygments.lexer.AnsiErlangShellLexer'>, <class 'pygments.lexers.julia.JuliaConsoleLexer'>: <class 'pygments.lexer.AnsiJuliaConsoleLexer'>, <class 'pygments.lexers.matlab.MatlabSessionLexer'>: <class 'pygments.lexer.AnsiMatlabSessionLexer'>, <class 'pygments.lexers.php.PsyshConsoleLexer'>: <class 'pygments.lexer.AnsiPsyshConsoleLexer'>, <class 'pygments.lexers.python.PythonConsoleLexer'>: <class 'pygments.lexer.AnsiPythonConsoleLexer'>, <class 'pygments.lexers.r.RConsoleLexer'>: <class 'pygments.lexer.AnsiRConsoleLexer'>, <class 'pygments.lexers.ruby.RubyConsoleLexer'>: <class 'pygments.lexer.AnsiRubyConsoleLexer'>, <class 'pygments.lexers.shell.BashSessionLexer'>: <class 'pygments.lexer.AnsiBashSessionLexer'>, <class 'pygments.lexers.shell.MSDOSSessionLexer'>: <class 'pygments.lexer.AnsiMSDOSSessionLexer'>, <class 'pygments.lexers.shell.PowerShellSessionLexer'>: <class 'pygments.lexer.AnsiPowerShellSessionLexer'>, <class 'pygments.lexers.shell.TcshSessionLexer'>: <class 'pygments.lexer.AnsiTcshSessionLexer'>, <class 'pygments.lexers.special.OutputLexer'>: <class 'pygments.lexer.AnsiOutputLexer'>, <class 'pygments.lexers.sql.PostgresConsoleLexer'>: <class 'pygments.lexer.AnsiPostgresConsoleLexer'>, <class 'pygments.lexers.sql.SqliteConsoleLexer'>: <class 'pygments.lexer.AnsiSqliteConsoleLexer'>}

Map original session lexers to their ANSI-capable variants.

click_extra.pygments.EXTRA_ANSI_CSS: dict[str, str] = {'Blink': 'animation: ansi-blink 1s step-end infinite', 'Bold': 'font-weight: bold', 'Faint': 'opacity: 0.5', 'Italic': 'font-style: italic', 'Overline': 'text-decoration: overline', 'Reverse': 'filter: invert(1)', 'Strikethrough': 'text-decoration: line-through', 'Underline': 'text-decoration: underline'}

All SGR text attribute CSS declarations.

Maps Token.Ansi component names to CSS declarations. These are kept out of the Pygments style dict (_ANSI_STYLES) to prevent Furo’s dark-mode CSS generator from injecting color: #D0D0D0 fallbacks that conflict with foreground color tokens.

Used by AnsiHtmlFormatter.get_token_style_defs to inject CSS rules that both standalone pygmentize and Furo’s dark-mode CSS generator pick up.

class click_extra.pygments.AnsiHtmlFormatter(**kwargs)[source]

Bases: HtmlFormatter

HTML formatter with ANSI color and hyperlink support.

Extends Pygments’ HtmlFormatter to handle compound Token.Ansi.* tokens by decomposing them into individual CSS classes, augments the base style with ANSI color definitions for the 256-color indexed palette, and renders OSC 8 hyperlinks as HTML <a> tags.

Intercept the style argument to augment it with ANSI color support.

Creates a new style instance that inherits from the one provided by the user, but updates its styles attribute with ANSI token definitions from _ANSI_STYLES.

name = 'ANSI HTML'

Full name for the formatter, in human-readable form.

aliases: ClassVar[list[str]] = ['ansi-html']

A list of short, unique identifiers that can be used to lookup the formatter from a list, e.g. using get_formatter_by_name().

format_unencoded(tokensource, outfile)[source]

Render tokens to HTML, converting OSC 8 link and 24-bit RGB markers to tags.

Replaces Token.AnsiLinkStart / Token.AnsiLinkEnd with Unicode Private Use Area markers, strips FG_/BG_ 24-bit RGB components from compound tokens and replaces them with PUA markers carrying the hex value, delegates to Pygments’ HTML rendering, then post-processes the output to swap markers for <a> and inline-styled <span> tags.

Return type:

None

get_token_style_defs(arg=None)[source]

Extend Pygments’ token CSS with rules for SGR attributes it cannot express.

Overriding get_token_style_defs (rather than get_style_defs) ensures that Furo’s dark-mode CSS generator, which calls this method directly, also picks up the extra rules built by _extra_ansi_css_lines.

get_ansi_style_defs(arg=None)[source]

Return only this formatter’s ANSI CSS, dropping Pygments’ base syntax-token rules.

The MkDocs plugin layers these over a theme’s own syntax highlighting, so it must not pull in the standard token rules (those would override the theme). Keeps the -Ansi-* token rules plus everything _extra_ansi_css_lines adds. Owning this selection here, next to the rules it returns, keeps the MkDocs plugin from hard-coding this formatter’s class names and CSS internals.

Return type:

str

click_extra.pytest module

Pytest fixtures and marks to help testing Click CLIs.

click_extra.pytest.runner()[source]

Runner fixture for click_extra.testing.CliRunner.

click_extra.pytest.invoke(runner)[source]

Invoke fixture shorthand for click_extra.testing.CliRunner.invoke().

click_extra.pytest.command_decorators(no_commands=False, no_groups=False, no_click=False, no_cloup=False, no_extra=False, with_parenthesis=True, with_types=False)[source]

Returns collection of Pytest parameters to test all command-like decorators.

Return type:

tuple[ParameterSet, ...]

Returns:

Pytest parameters covering each command-like decorator variant:

  • click.command

  • click.command()

  • cloup.command

  • cloup.command()

  • click_extra.command

  • click_extra.command()

  • click.group

  • click.group()

  • cloup.group

  • cloup.group()

  • click_extra.group

  • click_extra.group()

click_extra.pytest.option_decorators(no_options=False, no_arguments=False, no_click=False, no_cloup=False, no_extra=False, with_parenthesis=True, with_types=False)[source]

Returns collection of Pytest parameters to test all parameter-like decorators.

Return type:

tuple[ParameterSet, ...]

Returns:

Pytest parameters covering each parameter-like decorator variant:

  • click.option

  • click.option()

  • cloup.option

  • cloup.option()

  • click_extra.option

  • click_extra.option()

  • click.argument

  • click.argument()

  • cloup.argument

  • cloup.argument()

  • click_extra.argument

  • click_extra.argument()

click_extra.pytest.create_config(tmp_path)[source]

A generic fixture to produce a temporary configuration file.

click_extra.pytest.assert_output_regex()[source]

An assert-like utility for Pytest to compare CLI output against the regex.

Designed for the regexes defined above.

click_extra.spinner module

An indeterminate terminal spinner for long-running, blocking work.

Click ships click.progressbar(), but it is determinate: it needs a known length or an iterable to advance through. Some work has no measurable progress: a blocking subprocess, a network round-trip, a query whose duration is unknown. For those, the only honest feedback is “something is happening”.

Spinner fills that gap. It animates a small frame sequence on a daemon thread, so the caller can stay blocked in a single call (communicate(), urlopen(), …) while the spinner keeps turning:

from time import sleep

from click_extra import Spinner

with Spinner("Brewing tea"):
    sleep(5)  # A blocking call with no measurable progress.

Caution

The spinner draws with carriage returns and ANSI control codes, so it is a no-op whenever its output stream is not a TTY (a pipe, a file, a captured test buffer, a CI log), unless enabled is forced. This keeps redirected output and machine-readable formats clean.

Note

On Windows, Spinner.start() enables the console’s virtual-terminal processing so the ANSI control codes animate in place rather than print literally (⠋␛[0m ␛[K). Modern terminals (Windows Terminal, recent conhost) already have it on; this just covers older consoles.

class click_extra.spinner.Spinner(label='', *, frames=None, spinner=None, reverse=False, interval=None, delay=0.0, style=None, timer=False, stream=None, enabled=None, hide_cursor=True, beep=False)[source]

Bases: object

A thread-animated, indeterminate progress spinner usable as a context manager.

The animation runs on a background daemon thread, leaving the calling thread free to block on the actual work. Entering the context (or calling start()) begins the animation; leaving it (or calling stop()) halts the thread and erases the spinner line so it never lingers above the next output.

Note

A single Spinner instance drives one animation at a time. mpm and similar tools run their subprocesses sequentially, so one shared instance whose label is reassigned between steps is enough; for concurrent work, use one instance per thread.

Configure (but do not start) the spinner.

Parameters:
  • label (str | Callable[..., Any]) – text shown after the spinner glyph. As a special case, a bare @Spinner decorator passes the wrapped function here instead; it is detected and the label defaults to empty.

  • frames (Sequence[str] | None) – the animation frames, cycled in order. Defaults to SPINNER_FRAMES, or the spinner preset’s frames when given.

  • spinner (SpinnerPreset | None) – a SpinnerPreset from the SPINNERS catalog (spinner=SPINNERS["moon"]), supplying both frames and a tuned interval. An explicit frames or interval still overrides it.

  • reverse (bool) – cycle the frames backwards, spinning the animation the other way. Set it when the rotation runs counter to what you expect; it composes with any custom frames.

  • interval (float | None) – seconds between two frames. Defaults to 0.1, or the spinner preset’s interval when given.

  • delay (float) – seconds to wait before drawing the first frame. A non-zero delay keeps the spinner silent for calls that finish quickly, so it only surfaces once an operation is genuinely slow.

  • style (Style | None) – a Style applied to the spinner glyph, label and timer (Style(fg="cyan", bold=True)). Color is decoupled from animation: --no-color / NO_COLOR strip it while the spinner keeps spinning (see ProgressOption).

  • timer (bool | Callable[[float], str]) – append the elapsed wall-clock time to the spinner, and to any final ok() / fail() line. True uses the default compact format (2.3s, 1:05, then 1:02:03). Pass a callable (seconds: float) -> str to format the duration yourself, like timer=lambda s: f"{s / 60:.0f}m" for whole minutes.

  • stream (IO[str] | None) – where to draw; defaults to sys.stderr so the spinner never mixes into stdout data.

  • enabled (bool | None) – force the spinner on or off. None (the default) auto-detects, animating only when stream is a TTY.

  • hide_cursor (bool) – hide the text cursor while spinning and restore it on stop.

  • beep (bool) – ring the terminal bell once when the spinner stops. It fires only when the spinner was active, so a disabled or redirected spinner stays silent.

Raises:

ValueError – if style carries a color or attribute that cannot be rendered.

label: str

Text drawn after the spinner glyph.

Reassign it at any time while the spinner runs to reflect the current step; the animation thread reads it afresh on every frame.

property elapsed_time: float

Seconds elapsed since start(), frozen once stop() is called.

Returns 0.0 before the spinner has started.

property shown: bool

Whether the spinner has drawn at least one frame to its stream.

True only once an animation frame was actually rendered. It stays False for a disabled spinner (off a TTY, on a TERM=dumb terminal, or with enabled=False) and for a call that finishes within delay, before the first frame. Reset by start().

Use it to gate output that should mirror the spinner’s visibility. ok() and fail() write their line unconditionally, so an outcome is still recorded in a pipe or log; guard them with shown when you only want the finisher on screen after a spinner the user actually saw:

with Spinner("Baking bread") as spinner:
    bake()
    if spinner.shown:
        spinner.ok()
start()[source]

Begin animating on a background thread, unless the spinner is disabled.

A disabled spinner (non-TTY stream, or enabled=False) returns at once without spawning a thread or emitting anything (but still records the start time, so a later ok() / fail() can report a duration).

Return type:

None

stop()[source]

Halt the animation and erase the spinner line.

Idempotent and safe to call when the spinner never started. Restores the cursor and clears the line only if the animation actually drew to the terminal.

Return type:

None

echo(message='')[source]

Print message on its own line above the running spinner.

Click’s click.progressbar() and a bare print both fight the animation: a frame drawn between the cursor returns and the text mangles the line. echo() takes the same draw lock as the animation thread, erases the in-progress frame, writes message followed by a newline, and lets the next tick redraw the spinner underneath. It is safe to call from another thread while the spinner runs.

Output goes to the spinner’s own stream (stderr by default), so results written to stdout never need it. When the spinner is not animating (disabled, or a non-TTY stream), it degrades to a plain write of message with no control codes.

Return type:

None

ok(symbol=None, *, style=None)[source]

Stop the spinner and leave a persistent success line on screen.

Where stop() erases the spinner, ok() replaces the final frame with symbol followed by the current label (and the elapsed time when timer is set), then keeps that line. symbol defaults to the themed success glyph OK_GLYPH (), painted with the active theme’s success slot unless style overrides it. Color is stripped under --no-color / NO_COLOR; the glyph stays.

Return type:

None

fail(symbol=None, *, style=None)[source]

Stop the spinner and leave a persistent failure line on screen.

The failure counterpart of ok(), defaulting to KO_GLYPH () painted with the active theme’s error slot.

Return type:

None

class click_extra.spinner.ProgressOption(param_decls=None, is_flag=True, default=True, is_eager=True, expose_value=False, help='Show progress indicators during long operations. Disabled for non-interactive output (pipes, dumb terminals, CI) and by --accessible.', **kwargs)[source]

Bases: ExtraOption

A pre-configured --progress/--no-progress flag gating spinner display.

Resolves to a single boolean published at ctx.meta[click_extra.context.PROGRESS], which a CLI reads to decide whether to start a Spinner. The default is True; --accessible lowers it to False (via default_map) so a screen reader is never handed a spinning glyph.

Note

Spinner display is intentionally decoupled from color, even though both emit ANSI. A spinner is an interactivity concern, not a color one: it is built from cursor-control codes (hide-cursor, carriage return, clear-line), which the NO_COLOR standard explicitly does not govern – it “only signals the user’s intention regarding adding ANSI color to text output”. So --no-color / NO_COLOR strip the spinner’s colors but never hide it.

This matches how the wider ecosystem treats the two axes as orthogonal: cargo, npm, pip, Rich, indicatif and ora all gate progress on the terminal (and a dedicated --progress/--quiet knob), while NO_COLOR only affects color. Rich uses TERM=dumb – not NO_COLOR – as the signal to drop cursor-moving features like progress bars.

The spinner is therefore silenced by two things only, neither of them color:

  • non-interactive output – a pipe, file, CI log, or TERM=dumb terminal that cannot move the cursor (see Spinner._resolve_enabled);

  • explicit intent--no-progress or --accessible.

This option is eager. It no longer reads ctx.color, so its position relative to ColorOption is not load-bearing.

set_progress(ctx, param, value)[source]

Publish whether progress spinners may be shown.

Stores the resolved --progress flag at PROGRESS. Deliberately independent of color: see the ProgressOption note for why a spinner is gated on interactivity (TTY / TERM=dumb) and --accessible, never on --no-color / NO_COLOR.

Return type:

None

click_extra.spinner.progressbar(iterable=None, length=None, label=None, hidden=None, **kwargs)[source]

Drop-in for click.progressbar() honoring --progress / --no-progress.

Click’s own progress bar is determinate, the counterpart to the indeterminate Spinner. This thin wrapper gates it on the same PROGRESS flag the spinner uses, so a single --no-progress (or --accessible, which lowers the progress default) silences both.

Parameters:

hidden (bool | None) – tri-state. Left at its default None, the bar follows the resolved --progress flag: hidden when the user (or --accessible) turned progress off, shown otherwise. An explicit True or False forces the bar regardless, mirroring how an explicit color= argument overrides ctx.color on click.echo(). With no active context (the bar used outside a Click command) it defaults to shown.

Return type:

ProgressBar[TypeVar(V)]

Note

Only --no-progress is wired here. Color is already handled upstream: Click renders the bar through click.echo(), whose color=None resolves against ctx.color, so --no-color / NO_COLOR strip the bar’s ANSI without any work from this wrapper.

click_extra.spinner_presets module

The bundled catalog of terminal spinner presets.

Ported from cli-spinners, with frame intervals converted from milliseconds to seconds.

click_extra.spinner_presets.ASCII_SPINNER_FRAMES: Final = ('-', '\\', '|', '/')

Plain ASCII animation frames, for terminals or fonts lacking Unicode glyphs.

click_extra.spinner_presets.SPINNER_FRAMES: Final = ('⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏')

Default animation frames: the ubiquitous Braille-dots spinner.

Ten frames give a smooth rotation in any UTF-8 terminal. Fall back to ASCII_SPINNER_FRAMES where Braille glyphs are unavailable.

class click_extra.spinner_presets.SpinnerPreset(frames: tuple[str, ...], interval: float)[source]

Bases: NamedTuple

A named spinner animation: its frames and the interval they look best at.

The SPINNERS catalog is ported from cli-spinners, with intervals converted from milliseconds to seconds. Pass one to Spinner via its spinner argument.

Create new instance of SpinnerPreset(frames, interval)

frames: tuple[str, ...]

The animation frames, cycled in order.

interval: float

Seconds between two frames, tuned per spinner upstream.

click_extra.spinner_presets.SPINNERS: Final = {'aesthetic': (('▰▱▱▱▱▱▱', '▰▰▱▱▱▱▱', '▰▰▰▱▱▱▱', '▰▰▰▰▱▱▱', '▰▰▰▰▰▱▱', '▰▰▰▰▰▰▱', '▰▰▰▰▰▰▰', '▰▱▱▱▱▱▱'), 0.08), 'arc': (('◜', '◠', '◝', '◞', '◡', '◟'), 0.1), 'arrow': (('←', '↖', '↑', '↗', '→', '↘', '↓', '↙'), 0.1), 'arrow2': (('⬆️ ', '↗️ ', '➡️ ', '↘️ ', '⬇️ ', '↙️ ', '⬅️ ', '↖️ '), 0.08), 'arrow3': (('▹▹▹▹▹', '▸▹▹▹▹', '▹▸▹▹▹', '▹▹▸▹▹', '▹▹▹▸▹', '▹▹▹▹▸'), 0.12), 'balloon': ((' ', '.', 'o', 'O', '@', '*', ' '), 0.14), 'balloon2': (('.', 'o', 'O', '°', 'O', 'o', '.'), 0.12), 'betaWave': (('ρββββββ', 'βρβββββ', 'ββρββββ', 'βββρβββ', 'ββββρββ', 'βββββρβ', 'ββββββρ'), 0.08), 'binary': (('010010', '001100', '100101', '111010', '111101', '010111', '101011', '111000', '110011', '110101'), 0.08), 'bluePulse': (('🔹 ', '🔷 ', '🔵 ', '🔵 ', '🔷 '), 0.1), 'bounce': (('⠁', '⠂', '⠄', '⠂'), 0.12), 'bouncingBall': (('(     )', '(     )', '(     )', '(    )', '(     ●)', '(    )', '(     )', '(     )', '(     )', '(●     )'), 0.08), 'bouncingBar': (('[    ]', '[=   ]', '[==  ]', '[=== ]', '[====]', '[ ===]', '[  ==]', '[   =]', '[    ]', '[   =]', '[  ==]', '[ ===]', '[====]', '[=== ]', '[==  ]', '[=   ]'), 0.08), 'boxBounce': (('▖', '▘', '▝', '▗'), 0.12), 'boxBounce2': (('▌', '▀', '▐', '▄'), 0.1), 'christmas': (('🌲', '🎄'), 0.4), 'circle': (('◡', '⊙', '◠'), 0.12), 'circleHalves': (('◐', '◓', '◑', '◒'), 0.05), 'circleQuarters': (('◴', '◷', '◶', '◵'), 0.12), 'clock': (('🕛 ', '🕐 ', '🕑 ', '🕒 ', '🕓 ', '🕔 ', '🕕 ', '🕖 ', '🕗 ', '🕘 ', '🕙 ', '🕚 '), 0.1), 'dots': (('⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'), 0.08), 'dots10': (('⢄', '⢂', '⢁', '⡁', '⡈', '⡐', '⡠'), 0.08), 'dots11': (('⠁', '⠂', '⠄', '⡀', '⢀', '⠠', '⠐', '⠈'), 0.1), 'dots12': (('⢀⠀', '⡀⠀', '⠄⠀', '⢂⠀', '⡂⠀', '⠅⠀', '⢃⠀', '⡃⠀', '⠍⠀', '⢋⠀', '⡋⠀', '⠍⠁', '⢋⠁', '⡋⠁', '⠍⠉', '⠋⠉', '⠋⠉', '⠉⠙', '⠉⠙', '⠉⠩', '⠈⢙', '⠈⡙', '⢈⠩', '⡀⢙', '⠄⡙', '⢂⠩', '⡂⢘', '⠅⡘', '⢃⠨', '⡃⢐', '⠍⡐', '⢋⠠', '⡋⢀', '⠍⡁', '⢋⠁', '⡋⠁', '⠍⠉', '⠋⠉', '⠋⠉', '⠉⠙', '⠉⠙', '⠉⠩', '⠈⢙', '⠈⡙', '⠈⠩', '⠀⢙', '⠀⡙', '⠀⠩', '⠀⢘', '⠀⡘', '⠀⠨', '⠀⢐', '⠀⡐', '⠀⠠', '⠀⢀', '⠀⡀'), 0.08), 'dots13': (('⣼', '⣹', '⢻', '⠿', '⡟', '⣏', '⣧', '⣶'), 0.08), 'dots14': (('⠉⠉', '⠈⠙', '⠀⠹', '⠀⢸', '⠀⣰', '⢀⣠', '⣀⣀', '⣄⡀', '⣆⠀', '⡇⠀', '⠏⠀', '⠋⠁'), 0.08), 'dots2': (('⣾', '⣽', '⣻', '⢿', '⡿', '⣟', '⣯', '⣷'), 0.08), 'dots3': (('⠋', '⠙', '⠚', '⠞', '⠖', '⠦', '⠴', '⠲', '⠳', '⠓'), 0.08), 'dots4': (('⠄', '⠆', '⠇', '⠋', '⠙', '⠸', '⠰', '⠠', '⠰', '⠸', '⠙', '⠋', '⠇', '⠆'), 0.08), 'dots5': (('⠋', '⠙', '⠚', '⠒', '⠂', '⠂', '⠒', '⠲', '⠴', '⠦', '⠖', '⠒', '⠐', '⠐', '⠒', '⠓', '⠋'), 0.08), 'dots6': (('⠁', '⠉', '⠙', '⠚', '⠒', '⠂', '⠂', '⠒', '⠲', '⠴', '⠤', '⠄', '⠄', '⠤', '⠴', '⠲', '⠒', '⠂', '⠂', '⠒', '⠚', '⠙', '⠉', '⠁'), 0.08), 'dots7': (('⠈', '⠉', '⠋', '⠓', '⠒', '⠐', '⠐', '⠒', '⠖', '⠦', '⠤', '⠠', '⠠', '⠤', '⠦', '⠖', '⠒', '⠐', '⠐', '⠒', '⠓', '⠋', '⠉', '⠈'), 0.08), 'dots8': (('⠁', '⠁', '⠉', '⠙', '⠚', '⠒', '⠂', '⠂', '⠒', '⠲', '⠴', '⠤', '⠄', '⠄', '⠤', '⠠', '⠠', '⠤', '⠦', '⠖', '⠒', '⠐', '⠐', '⠒', '⠓', '⠋', '⠉', '⠈', '⠈'), 0.08), 'dots8Bit': (('⠀', '⠁', '⠂', '⠃', '⠄', '⠅', '⠆', '⠇', '⡀', '⡁', '⡂', '⡃', '⡄', '⡅', '⡆', '⡇', '⠈', '⠉', '⠊', '⠋', '⠌', '⠍', '⠎', '⠏', '⡈', '⡉', '⡊', '⡋', '⡌', '⡍', '⡎', '⡏', '⠐', '⠑', '⠒', '⠓', '⠔', '⠕', '⠖', '⠗', '⡐', '⡑', '⡒', '⡓', '⡔', '⡕', '⡖', '⡗', '⠘', '⠙', '⠚', '⠛', '⠜', '⠝', '⠞', '⠟', '⡘', '⡙', '⡚', '⡛', '⡜', '⡝', '⡞', '⡟', '⠠', '⠡', '⠢', '⠣', '⠤', '⠥', '⠦', '⠧', '⡠', '⡡', '⡢', '⡣', '⡤', '⡥', '⡦', '⡧', '⠨', '⠩', '⠪', '⠫', '⠬', '⠭', '⠮', '⠯', '⡨', '⡩', '⡪', '⡫', '⡬', '⡭', '⡮', '⡯', '⠰', '⠱', '⠲', '⠳', '⠴', '⠵', '⠶', '⠷', '⡰', '⡱', '⡲', '⡳', '⡴', '⡵', '⡶', '⡷', '⠸', '⠹', '⠺', '⠻', '⠼', '⠽', '⠾', '⠿', '⡸', '⡹', '⡺', '⡻', '⡼', '⡽', '⡾', '⡿', '⢀', '⢁', '⢂', '⢃', '⢄', '⢅', '⢆', '⢇', '⣀', '⣁', '⣂', '⣃', '⣄', '⣅', '⣆', '⣇', '⢈', '⢉', '⢊', '⢋', '⢌', '⢍', '⢎', '⢏', '⣈', '⣉', '⣊', '⣋', '⣌', '⣍', '⣎', '⣏', '⢐', '⢑', '⢒', '⢓', '⢔', '⢕', '⢖', '⢗', '⣐', '⣑', '⣒', '⣓', '⣔', '⣕', '⣖', '⣗', '⢘', '⢙', '⢚', '⢛', '⢜', '⢝', '⢞', '⢟', '⣘', '⣙', '⣚', '⣛', '⣜', '⣝', '⣞', '⣟', '⢠', '⢡', '⢢', '⢣', '⢤', '⢥', '⢦', '⢧', '⣠', '⣡', '⣢', '⣣', '⣤', '⣥', '⣦', '⣧', '⢨', '⢩', '⢪', '⢫', '⢬', '⢭', '⢮', '⢯', '⣨', '⣩', '⣪', '⣫', '⣬', '⣭', '⣮', '⣯', '⢰', '⢱', '⢲', '⢳', '⢴', '⢵', '⢶', '⢷', '⣰', '⣱', '⣲', '⣳', '⣴', '⣵', '⣶', '⣷', '⢸', '⢹', '⢺', '⢻', '⢼', '⢽', '⢾', '⢿', '⣸', '⣹', '⣺', '⣻', '⣼', '⣽', '⣾', '⣿'), 0.08), 'dots9': (('⢹', '⢺', '⢼', '⣸', '⣇', '⡧', '⡗', '⡏'), 0.08), 'dotsCircle': (('⢎ ', '⠎⠁', '⠊⠑', '⠈⠱', ' ⡱', '⢀⡰', '⢄⡠', '⢆⡀'), 0.08), 'dqpb': (('d', 'q', 'p', 'b'), 0.1), 'dwarfFortress': ((' ██████£££  ', '☺██████£££  ', '☺██████£££  ', '☺▓█████£££  ', '☺▓█████£££  ', '☺▒█████£££  ', '☺▒█████£££  ', '☺░█████£££  ', '☺░█████£££  ', '☺ █████£££  ', ' ☺█████£££  ', ' ☺█████£££  ', ' ☺▓████£££  ', ' ☺▓████£££  ', ' ☺▒████£££  ', ' ☺▒████£££  ', ' ☺░████£££  ', ' ☺░████£££  ', ' ████£££  ', '  ☺████£££  ', '  ☺████£££  ', '  ☺▓███£££  ', '  ☺▓███£££  ', '  ☺▒███£££  ', '  ☺▒███£££  ', '  ☺░███£££  ', '  ☺░███£££  ', '  ███£££  ', '   ☺███£££  ', '   ☺███£££  ', '   ☺▓██£££  ', '   ☺▓██£££  ', '   ☺▒██£££  ', '   ☺▒██£££  ', '   ☺░██£££  ', '   ☺░██£££  ', '   ██£££  ', '    ☺██£££  ', '    ☺██£££  ', '    ☺▓█£££  ', '    ☺▓█£££  ', '    ☺▒█£££  ', '    ☺▒█£££  ', '    ☺░█£££  ', '    ☺░█£££  ', '    █£££  ', '     ☺█£££  ', '     ☺█£££  ', '     ☺▓£££  ', '     ☺▓£££  ', '     ☺▒£££  ', '     ☺▒£££  ', '     ☺░£££  ', '     ☺░£££  ', '     £££  ', '      ☺£££  ', '      ☺£££  ', '      ☺▓££  ', '      ☺▓££  ', '      ☺▒££  ', '      ☺▒££  ', '      ☺░££  ', '      ☺░££  ', '      ££  ', '       ☺££  ', '       ☺££  ', '       ☺▓£  ', '       ☺▓£  ', '       ☺▒£  ', '       ☺▒£  ', '       ☺░£  ', '       ☺░£  ', '       £  ', '        ☺£  ', '        ☺£  ', '        ☺▓  ', '        ☺▓  ', '        ☺▒  ', '        ☺▒  ', '        ☺░  ', '        ☺░  ', '           ', '          &', '        ☼&', '       &', '       ☺☼  &', '      ☺☼  & ', '         & ', '        &  ', '        &  ', '       &   ', '       &   ', '      &    ', '‼      &    ', '      &     ', '      &     ', '     &     ', '     &     ', '    &      ', '    &    £  ', '   &    ░£  ', '   &    ▒£  ', '  &     ▓£  ', '  &     ££  ', ' &     ░££  ', ' &     ▒££  ', '&      ▓££  ', '&      £££  ', '      ░£££  ', '      ▒£££  ', '      ▓£££  ', '      █£££  ', '     ░█£££  ', '     ▒█£££  ', '     ▓█£££  ', '     ██£££  ', '    ░██£££  ', '    ▒██£££  ', '    ▓██£££  ', '    ███£££  ', '   ░███£££  ', '   ▒███£££  ', '   ▓███£££  ', '   ████£££  ', '  ░████£££  ', '  ▒████£££  ', '  ▓████£££  ', '  █████£££  ', ' ░█████£££  ', ' ▒█████£££  ', ' ▓█████£££  ', ' ██████£££  ', ' ██████£££  '), 0.08), 'earth': (('🌍 ', '🌎 ', '🌏 '), 0.18), 'fingerDance': (('🤘 ', '🤟 ', '🖖 ', '✋ ', '🤚 ', '👆 '), 0.16), 'fish': (('~~~~~~~~~~~~~~~~~~~~', '> ~~~~~~~~~~~~~~~~~~', 'º> ~~~~~~~~~~~~~~~~~', '(º> ~~~~~~~~~~~~~~~~', '((º> ~~~~~~~~~~~~~~~', '<((º> ~~~~~~~~~~~~~~', '><((º> ~~~~~~~~~~~~~', ' ><((º> ~~~~~~~~~~~~', '~ ><((º> ~~~~~~~~~~~', '~~ <>((º> ~~~~~~~~~~', '~~~ ><((º> ~~~~~~~~~', '~~~~ <>((º> ~~~~~~~~', '~~~~~ ><((º> ~~~~~~~', '~~~~~~ <>((º> ~~~~~~', '~~~~~~~ ><((º> ~~~~~', '~~~~~~~~ <>((º> ~~~~', '~~~~~~~~~ ><((º> ~~~', '~~~~~~~~~~ <>((º> ~~', '~~~~~~~~~~~ ><((º> ~', '~~~~~~~~~~~~ <>((º> ', '~~~~~~~~~~~~~ ><((º>', '~~~~~~~~~~~~~~ <>((º', '~~~~~~~~~~~~~~~ ><((', '~~~~~~~~~~~~~~~~ <>(', '~~~~~~~~~~~~~~~~~ ><', '~~~~~~~~~~~~~~~~~~ <', '~~~~~~~~~~~~~~~~~~~~'), 0.08), 'fistBump': (('🤜\u3000\u3000\u3000\u3000🤛 ', '🤜\u3000\u3000\u3000\u3000🤛 ', '🤜\u3000\u3000\u3000\u3000🤛 ', '\u3000🤜\u3000\u3000🤛\u3000 ', '\u3000\u3000🤜🤛\u3000\u3000 ', '\u3000🤜✨🤛\u3000\u3000 ', '🤜\u3000✨\u3000🤛\u3000 '), 0.08), 'flip': (('_', '_', '_', '-', '`', '`', "'", '´', '-', '_', '_', '_'), 0.07), 'grenade': (('،  ', '′  ', ' ´ ', ' ', '  ⸌', '  ⸊', '  |', '  ⁎', '  ⁕', ' ', '  ⁓', '   ', '   ', '   '), 0.08), 'growHorizontal': (('▏', '▎', '▍', '▌', '▋', '▊', '▉', '▊', '▋', '▌', '▍', '▎'), 0.12), 'growVertical': (('▁', '▃', '▄', '▅', '▆', '▇', '▆', '▅', '▄', '▃'), 0.12), 'hamburger': (('☱', '☲', '☴'), 0.1), 'hearts': (('💛 ', '💙 ', '💜 ', '💚 ', '💗 '), 0.1), 'layer': (('-', '=', '≡'), 0.15), 'line': (('-', '\\', '|', '/'), 0.13), 'line2': (('⠂', '-', '–', '—', '–', '-'), 0.1), 'material': (('█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁', '██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁', '███▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁', '████▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁', '██████▁▁▁▁▁▁▁▁▁▁▁▁▁▁', '██████▁▁▁▁▁▁▁▁▁▁▁▁▁▁', '███████▁▁▁▁▁▁▁▁▁▁▁▁▁', '████████▁▁▁▁▁▁▁▁▁▁▁▁', '█████████▁▁▁▁▁▁▁▁▁▁▁', '█████████▁▁▁▁▁▁▁▁▁▁▁', '██████████▁▁▁▁▁▁▁▁▁▁', '███████████▁▁▁▁▁▁▁▁▁', '█████████████▁▁▁▁▁▁▁', '██████████████▁▁▁▁▁▁', '██████████████▁▁▁▁▁▁', '▁██████████████▁▁▁▁▁', '▁██████████████▁▁▁▁▁', '▁██████████████▁▁▁▁▁', '▁▁██████████████▁▁▁▁', '▁▁▁██████████████▁▁▁', '▁▁▁▁█████████████▁▁▁', '▁▁▁▁██████████████▁▁', '▁▁▁▁██████████████▁▁', '▁▁▁▁▁██████████████▁', '▁▁▁▁▁██████████████▁', '▁▁▁▁▁██████████████▁', '▁▁▁▁▁▁██████████████', '▁▁▁▁▁▁██████████████', '▁▁▁▁▁▁▁█████████████', '▁▁▁▁▁▁▁█████████████', '▁▁▁▁▁▁▁▁████████████', '▁▁▁▁▁▁▁▁████████████', '▁▁▁▁▁▁▁▁▁███████████', '▁▁▁▁▁▁▁▁▁███████████', '▁▁▁▁▁▁▁▁▁▁██████████', '▁▁▁▁▁▁▁▁▁▁██████████', '▁▁▁▁▁▁▁▁▁▁▁▁████████', '▁▁▁▁▁▁▁▁▁▁▁▁▁███████', '▁▁▁▁▁▁▁▁▁▁▁▁▁▁██████', '▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████', '▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████', '█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████', '██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███', '██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███', '███▁▁▁▁▁▁▁▁▁▁▁▁▁▁███', '████▁▁▁▁▁▁▁▁▁▁▁▁▁▁██', '█████▁▁▁▁▁▁▁▁▁▁▁▁▁▁█', '█████▁▁▁▁▁▁▁▁▁▁▁▁▁▁█', '██████▁▁▁▁▁▁▁▁▁▁▁▁▁█', '████████▁▁▁▁▁▁▁▁▁▁▁▁', '█████████▁▁▁▁▁▁▁▁▁▁▁', '█████████▁▁▁▁▁▁▁▁▁▁▁', '█████████▁▁▁▁▁▁▁▁▁▁▁', '█████████▁▁▁▁▁▁▁▁▁▁▁', '███████████▁▁▁▁▁▁▁▁▁', '████████████▁▁▁▁▁▁▁▁', '████████████▁▁▁▁▁▁▁▁', '██████████████▁▁▁▁▁▁', '██████████████▁▁▁▁▁▁', '▁██████████████▁▁▁▁▁', '▁██████████████▁▁▁▁▁', '▁▁▁█████████████▁▁▁▁', '▁▁▁▁▁████████████▁▁▁', '▁▁▁▁▁████████████▁▁▁', '▁▁▁▁▁▁███████████▁▁▁', '▁▁▁▁▁▁▁▁█████████▁▁▁', '▁▁▁▁▁▁▁▁█████████▁▁▁', '▁▁▁▁▁▁▁▁▁█████████▁▁', '▁▁▁▁▁▁▁▁▁█████████▁▁', '▁▁▁▁▁▁▁▁▁▁█████████▁', '▁▁▁▁▁▁▁▁▁▁▁████████▁', '▁▁▁▁▁▁▁▁▁▁▁████████▁', '▁▁▁▁▁▁▁▁▁▁▁▁███████▁', '▁▁▁▁▁▁▁▁▁▁▁▁███████▁', '▁▁▁▁▁▁▁▁▁▁▁▁▁███████', '▁▁▁▁▁▁▁▁▁▁▁▁▁███████', '▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████', '▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████', '▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████', '▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████', '▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███', '▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███', '▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██', '▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██', '▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██', '▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█', '▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█', '▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█', '▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁', '▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁', '▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁', '▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁'), 0.017), 'mindblown': (('😐 ', '😐 ', '😮 ', '😮 ', '😦 ', '😦 ', '😧 ', '😧 ', '🤯 ', '💥 ', '✨ ', '\u3000 ', '\u3000 ', '\u3000 '), 0.16), 'monkey': (('🙈 ', '🙈 ', '🙉 ', '🙊 '), 0.3), 'moon': (('🌑 ', '🌒 ', '🌓 ', '🌔 ', '🌕 ', '🌖 ', '🌗 ', '🌘 '), 0.08), 'noise': (('▓', '▒', '░'), 0.1), 'orangeBluePulse': (('🔸 ', '🔶 ', '🟠 ', '🟠 ', '🔶 ', '🔹 ', '🔷 ', '🔵 ', '🔵 ', '🔷 '), 0.1), 'orangePulse': (('🔸 ', '🔶 ', '🟠 ', '🟠 ', '🔶 '), 0.1), 'pipe': (('┤', '┘', '┴', '└', '├', '┌', '┬', '┐'), 0.1), 'point': (('∙∙∙', '●∙∙', '∙●∙', '∙∙●', '∙∙∙'), 0.125), 'pong': (('▐⠂       ▌', '▐⠈       ▌', '▐       ▌', '▐       ▌', '▐       ▌', '▐       ▌', '▐       ▌', '▐       ▌', '▐       ▌', '▐       ▌', '▐       ▌', '▐       ▌', '▐      ▌', '▐      ▌', '▐       ⠂▌', '▐       ⠠▌', '▐       ⡀▌', '▐      ▌', '▐      ▌', '▐       ▌', '▐       ▌', '▐       ▌', '▐       ▌', '▐       ▌', '▐       ▌', '▐       ▌', '▐       ▌', '▐       ▌', '▐       ▌', '▐⠠       ▌'), 0.08), 'rollingLine': (('/  ', ' - ', ' \\ ', '  |', '  |', ' \\ ', ' - ', '/  '), 0.08), 'runner': (('🚶 ', '🏃 '), 0.14), 'sand': (('⠁', '⠂', '⠄', '⡀', '⡈', '⡐', '⡠', '⣀', '⣁', '⣂', '⣄', '⣌', '⣔', '⣤', '⣥', '⣦', '⣮', '⣶', '⣷', '⣿', '⡿', '⠿', '⢟', '⠟', '⡛', '⠛', '⠫', '⢋', '⠋', '⠍', '⡉', '⠉', '⠑', '⠡', '⢁'), 0.08), 'shark': (('▐|\\____________▌', '▐_|\\___________▌', '▐__|\\__________▌', '▐___|\\_________▌', '▐____|\\________▌', '▐_____|\\_______▌', '▐______|\\______▌', '▐_______|\\_____▌', '▐________|\\____▌', '▐_________|\\___▌', '▐__________|\\__▌', '▐___________|\\_▌', '▐____________|\\▌', '▐____________/|▌', '▐___________/|_▌', '▐__________/|__▌', '▐_________/|___▌', '▐________/|____▌', '▐_______/|_____▌', '▐______/|______▌', '▐_____/|_______▌', '▐____/|________▌', '▐___/|_________▌', '▐__/|__________▌', '▐_/|___________▌', '▐/|____________▌'), 0.12), 'simpleDots': (('.  ', '.. ', '...', '   '), 0.4), 'simpleDotsScrolling': (('.  ', '.. ', '...', ' ..', '  .', '   '), 0.2), 'smiley': (('😄 ', '😝 '), 0.2), 'soccerHeader': ((' 🧑⚽️       🧑 ', '🧑  ⚽️      🧑 ', '🧑   ⚽️     🧑 ', '🧑    ⚽️    🧑 ', '🧑     ⚽️   🧑 ', '🧑      ⚽️  🧑 ', '🧑       ⚽️🧑  ', '🧑      ⚽️  🧑 ', '🧑     ⚽️   🧑 ', '🧑    ⚽️    🧑 ', '🧑   ⚽️     🧑 ', '🧑  ⚽️      🧑 '), 0.08), 'speaker': (('🔈 ', '🔉 ', '🔊 ', '🔉 '), 0.16), 'squareCorners': (('◰', '◳', '◲', '◱'), 0.18), 'squish': (('╫', '╪'), 0.1), 'star': (('✶', '✸', '✹', '✺', '✹', '✷'), 0.07), 'star2': (('+', 'x', '*'), 0.08), 'timeTravel': (('🕛 ', '🕚 ', '🕙 ', '🕘 ', '🕗 ', '🕖 ', '🕕 ', '🕔 ', '🕓 ', '🕒 ', '🕑 ', '🕐 '), 0.1), 'toggle': (('⊶', '⊷'), 0.25), 'toggle10': (('㊂', '㊀', '㊁'), 0.1), 'toggle11': (('⧇', '⧆'), 0.05), 'toggle12': (('☗', '☖'), 0.12), 'toggle13': (('=', '*', '-'), 0.08), 'toggle2': (('▫', '▪'), 0.08), 'toggle3': (('□', '■'), 0.12), 'toggle4': (('■', '□', '▪', '▫'), 0.1), 'toggle5': (('▮', '▯'), 0.1), 'toggle6': (('ဝ', '၀'), 0.3), 'toggle7': (('⦾', '⦿'), 0.08), 'toggle8': (('◍', '◌'), 0.1), 'toggle9': (('◉', '◎'), 0.1), 'triangle': (('◢', '◣', '◤', '◥'), 0.05), 'weather': (('☀️ ', '☀️ ', '☀️ ', '🌤 ', '⛅️ ', '🌥 ', '☁️ ', '🌧 ', '🌨 ', '🌧 ', '🌨 ', '🌧 ', '🌨 ', '⛈ ', '🌨 ', '🌧 ', '🌨 ', '☁️ ', '🌥 ', '⛅️ ', '🌤 ', '☀️ ', '☀️ '), 0.1)}

Named spinner animations ported from cli-spinners, keyed by name.

Each value is a SpinnerPreset bundling frames and a tuned interval. Select one with Spinner’s spinner argument:

from click_extra import Spinner, SPINNERS

with Spinner("Brewing tea", spinner=SPINNERS["moon"]):
    ...

Unlike the upstream \b-based renderers, Spinner redraws the whole line, so the multi-character animations (bouncingBar, pong, shark, …) render correctly here.

click_extra.table module

Collection of table rendering utilities.

class click_extra.table.TableFormat(*values)[source]

Bases: Enum

Enumeration of supported table formats.

Hard-coded to be in alphabetical order. Content of this enum is checked in unit tests.

Warning

The youtrack format is missing in action from any official JetBrains documentation. It will be removed in python-tabulate v0.11.

ALIGNED = 'aligned'
ASCIIDOC = 'asciidoc'
COLON_GRID = 'colon-grid'
CSV = 'csv'
CSV_EXCEL = 'csv-excel'
CSV_EXCEL_TAB = 'csv-excel-tab'
CSV_UNIX = 'csv-unix'
DOUBLE_GRID = 'double-grid'
DOUBLE_OUTLINE = 'double-outline'
FANCY_GRID = 'fancy-grid'
FANCY_OUTLINE = 'fancy-outline'
GITHUB = 'github'
GRID = 'grid'
HEAVY_GRID = 'heavy-grid'
HEAVY_OUTLINE = 'heavy-outline'
HJSON = 'hjson'
HTML = 'html'
JIRA = 'jira'
JSON = 'json'
JSON5 = 'json5'
JSONC = 'jsonc'
LATEX = 'latex'
LATEX_BOOKTABS = 'latex-booktabs'
LATEX_LONGTABLE = 'latex-longtable'
LATEX_RAW = 'latex-raw'
MEDIAWIKI = 'mediawiki'
MIXED_GRID = 'mixed-grid'
MIXED_OUTLINE = 'mixed-outline'
MOINMOIN = 'moinmoin'
ORGTBL = 'orgtbl'
OUTLINE = 'outline'
PIPE = 'pipe'
PLAIN = 'plain'
PRESTO = 'presto'
PRETTY = 'pretty'
PSQL = 'psql'
ROUNDED_GRID = 'rounded-grid'
ROUNDED_OUTLINE = 'rounded-outline'
RST = 'rst'
SIMPLE = 'simple'
SIMPLE_GRID = 'simple-grid'
SIMPLE_OUTLINE = 'simple-outline'
TEXTILE = 'textile'
TOML = 'toml'
TSV = 'tsv'
UNSAFEHTML = 'unsafehtml'
VERTICAL = 'vertical'
XML = 'xml'
YAML = 'yaml'
YOUTRACK = 'youtrack'
property is_markup: bool

Whether this format is a markup rendering.

Markup formats have ANSI color codes stripped from their output by default. Use the --color flag to preserve them.

click_extra.table.MARKUP_FORMATS = frozenset({TableFormat.ASCIIDOC, TableFormat.CSV, TableFormat.CSV_EXCEL, TableFormat.CSV_EXCEL_TAB, TableFormat.CSV_UNIX, TableFormat.GITHUB, TableFormat.HJSON, TableFormat.HTML, TableFormat.JIRA, TableFormat.JSON, TableFormat.JSON5, TableFormat.JSONC, TableFormat.LATEX, TableFormat.LATEX_BOOKTABS, TableFormat.LATEX_LONGTABLE, TableFormat.LATEX_RAW, TableFormat.MEDIAWIKI, TableFormat.MOINMOIN, TableFormat.ORGTBL, TableFormat.PIPE, TableFormat.RST, TableFormat.TEXTILE, TableFormat.TOML, TableFormat.TSV, TableFormat.UNSAFEHTML, TableFormat.XML, TableFormat.YAML, TableFormat.YOUTRACK})

Subset of table formats that are considered as markup rendering.

click_extra.table.DEFAULT_FORMAT = TableFormat.ROUNDED_OUTLINE

Default table format, if none is specified.

click_extra.table.RECORD_KEY = 'record'

Key used for each record in structured formats that require named containers (TOML [[record]], XML <record>).

click_extra.table.XML_ROOT_KEY = 'records'

Root element name for XML table output.

click_extra.table.SERIALIZATION_FORMATS = frozenset({TableFormat.HJSON, TableFormat.JSON, TableFormat.JSON5, TableFormat.JSONC, TableFormat.TOML, TableFormat.XML, TableFormat.YAML})

Structured serialization formats whose renderers escape raw ESC bytes, making post-render strip_ansi() ineffective.

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

Render a table and return it as a string.

Parameters:

sort_key (Callable[[Sequence[str | None]], Any] | None) – Optional callable passed to sorted() as the key argument. When provided, rows are sorted before rendering.

Return type:

str

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

Render a table and print it to the console.

For markup formats, ANSI color codes are stripped from cell values before rendering unless --color is explicitly set.

Parameters:

sort_key (Callable[[Sequence[str | None]], Any] | None) – Optional callable passed to sorted() as the key argument. When provided, rows are sorted before rendering.

Return type:

None

click_extra.table.serialize_data(data, table_format, *, default=None, root_element='records', **kwargs)[source]

Serialize arbitrary Python data to a structured format.

Unlike render_table() which expects tabular rows and headers, this function accepts any JSON-compatible data structure (dicts, lists, nested combinations) and serializes it to the requested format.

Only formats in SERIALIZATION_FORMATS are supported.

Parameters:
  • data (Any) – Arbitrary data to serialize (dicts, lists, scalars).

  • table_format (TableFormat) – Target serialization format.

  • default (Callable | None) – Fallback serializer for types not natively supported. Defaults to str, so Path and similar types are stringified automatically. Set to a custom callable for different behavior.

  • root_element (str) – Root element name for XML output.

  • kwargs – Extra keyword arguments forwarded to the underlying serializer (like sort_keys or indent for JSON).

Raises:

ValueError – If the format is not a serialization format.

Return type:

str

click_extra.table.print_data(data, table_format, *, default=None, root_element='records', package='click-extra', **kwargs)[source]

Serialize arbitrary Python data and print it to the console.

Wraps serialize_data() with user-friendly error handling for missing optional dependencies.

Parameters:
  • data (Any) – Arbitrary data to serialize.

  • table_format (TableFormat) – Target serialization format.

  • default (Callable | None) – Fallback serializer for custom types. Defaults to str.

  • root_element (str) – Root element name for XML output.

  • package (str) – Package name for install instructions in error messages.

  • kwargs – Extra keyword arguments forwarded to the underlying serializer.

Return type:

None

class click_extra.table.TableFormatOption(param_decls=None, type=EnumChoice('aligned', 'asciidoc', 'colon-grid', 'csv', 'csv-excel', 'csv-excel-tab', 'csv-unix', 'double-grid', 'double-outline', 'fancy-grid', 'fancy-outline', 'github', 'grid', 'heavy-grid', 'heavy-outline', 'hjson', 'html', 'jira', 'json', 'json5', 'jsonc', 'latex', 'latex-booktabs', 'latex-longtable', 'latex-raw', 'mediawiki', 'mixed-grid', 'mixed-outline', 'moinmoin', 'orgtbl', 'outline', 'pipe', 'plain', 'presto', 'pretty', 'psql', 'rounded-grid', 'rounded-outline', 'rst', 'simple', 'simple-grid', 'simple-outline', 'textile', 'toml', 'tsv', 'unsafehtml', 'vertical', 'xml', 'yaml', 'youtrack'), default=TableFormat.ROUNDED_OUTLINE, expose_value=False, is_eager=True, help='Rendering style of tables.', **kwargs)[source]

Bases: ExtraOption

A pre-configured option that is adding a --table-format flag to select the rendering style of a table.

The selected table format ID is made available in the context in ctx.meta[click_extra.context.TABLE_FORMAT], and two helper methods are added to the context:

  • ctx.render_table(table_data, headers, **kwargs): renders and returns the table as a string,

  • ctx.print_table(table_data, headers, **kwargs): renders and prints the table to the console.

Where:

  • table_data is a 2-dimensional iterable of iterables for rows and cells values,

  • headers is a list of string to be used as column headers,

  • **kwargs are any extra keyword arguments supported by the underlying table formatting function.

init_formatter(ctx, param, table_format)[source]

Save in the context: table_format, render_table & print_table.

Return type:

None

class click_extra.table.ColumnSpec(id, label, description='')[source]

Bases: object

Rich description of a single column in a rendered table.

Three fields, all required-by-convention even though description defaults to empty so quick prototypes do not have to write a sentence for every column:

  • id: stable, snake_case identifier used by --columns to address the column, to key structured-format serializations, and to thread state through click_extra.context.COLUMNS.

  • label: the human-readable header shown at the top of the rendered table.

  • description: a MyST/Markdown blurb describing what the column represents. Used to auto-generate the column reference in the documentation.

Note

Frozen + slots: instances are immutable and lightweight. Tuples of ColumnSpec are intended to be defined as module-level constants (like click_extra.parameters.ShowParamsOption.TABLE_HEADERS).

id: str

Stable, snake_case identifier addressing this column from CLI flags and code.

label: str

Human-readable header label rendered at the top of the table.

description: str

MyST/Markdown description of what the column carries.

Used to auto-generate the Available columns section in the docs via the show_params_columns_table MyST substitution. Plain text without inline markup is fine: links and emphasis are optional sugar.

click_extra.table.render_columns_markdown_table(columns)[source]

Render an iterable of ColumnSpec as a 2-column Markdown table.

Output shape:

| Column | Description |
| :--- | :--- |
| `Label` | description |
...

Suitable for inlining into MyST documents via myst_substitutions so the Available columns reference can be auto-generated from a single source of truth.

Return type:

str

click_extra.table.select_columns(columns, selected_ids)[source]

Filter and reorder columns according to selected_ids.

Returns columns unchanged when selected_ids is falsy (no projection). Otherwise yields the matching ColumnSpec in the order selected_ids specifies, SQL-SELECT-style. Raises KeyError for unknown IDs so the caller can convert it into a click.UsageError.

Return type:

tuple[ColumnSpec, ...]

click_extra.table.select_row(row, selected_ids, canonical_ids)[source]

Build a positional row by reading cells from row in the selection order.

Falls back to canonical_ids when selected_ids is empty / unset, so the row preserves its canonical column order in the absence of any user selection.

Return type:

tuple

class click_extra.table.ColumnsType(accepted_ids=())[source]

Bases: MultiChoice

Column-flavored alias of click_extra.types.MultiChoice.

Pins the comma separator and case-sensitive matching (column IDs are snake_case identifiers, not free-form strings), and renames the metavar fallback to COLUMNS instead of the generic MULTI. The accepted_ids constructor keyword is a column-flavored alias of MultiChoice.choices.

Initialize the type.

Parameters:
  • choices – the accepted values. When non-empty, convert() rejects unknown tokens with fail. When empty, the type behaves as a pure separator-aware parser and leaves validation to the consumer.

  • separator – the token boundary. Use any single character; this also drives the metavar rendering ([a<sep>b<sep>c]).

  • case_sensitive – when False, tokens match choices case-insensitively and the returned tuple holds the canonical (original-case) values from choices.

name: str = 'columns'

the descriptive name of this type

class click_extra.table.ColumnsOption(param_decls=None, columns=None, type=None, default=(), expose_value=False, is_eager=True, help='Restrict and reorder table columns, SQL SELECT-style. Comma-separated list of column IDs. Default: all columns in canonical order.', **kwargs)[source]

Bases: ExtraOption

A --columns option that lets users restrict and reorder table columns.

Accepts a comma-separated list of column IDs, SQL-SELECT-style:

$ my-cli --columns id,spec,value --show-params

The selection is stored in ctx.meta[click_extra.context.COLUMNS] and consumed by table-rendering callbacks (like click_extra.parameters.ShowParamsOption) to project rows + headers before rendering.

Pass columns= at construction time with the column registry the option should advertise: the help text then lists the accepted IDs and the default selection, and the callback validates the user input against that registry so unknown IDs fail fast with a click.UsageError. Without columns=, the option stays generic: it parses any IDs and leaves validation to the downstream consumer.

Empty / unset means render every column in canonical order: the default behavior, indistinguishable from not passing --columns at all.

columns: tuple[ColumnSpec, ...]

Column registry this option advertises and validates against (may be empty).

init_columns(ctx, param, columns)[source]

Store the selected column IDs on the context for later projection.

Validation of the IDs against the registry happens inside convert(), before this callback runs, so this just threads the parsed selection onto the context.

Return type:

None

class click_extra.table.SortByOption(*header_defs, param_decls=None, default=None, expose_value=False, cell_key=None, help='Sort table by this column. Repeat to set priority.', **kwargs)[source]

Bases: ExtraOption

A --sort-by option whose choices are derived from column definitions.

Stores the selected column IDs in ctx.meta[click_extra.context.SORT_BY] and bakes a row sort into ctx.print_table so that table output is automatically sorted, without changing its (table_data, headers) call contract. The option accepts multiple=True, so users can repeat --sort-by to define a multi-column sort priority.

@command
@table_format_option
@sort_by_option(
    ("Package ID", "package_id"),
    ("Name", "package_name"),
    ("Manager", "manager_id"),
    ("Version", None),
)
@pass_context
def my_cmd(ctx):
    ctx.print_table(rows, headers)
init_sort(ctx, param, sort_columns)[source]

Bake the row sort key into ctx.print_table.

Builds the sort key from this option’s column definitions and the selected sort_columns, then rebinds ctx.print_table to print_table() with that key applied. The call contract is the same sorted or not: ctx.print_table(table_data, headers).

Return type:

None

click_extra.telemetry module

Telemetry utilities.

class click_extra.telemetry.TelemetryOption(param_decls=None, default=False, expose_value=False, envvar=None, show_envvar=True, help='Collect telemetry and usage data.', **kwargs)[source]

Bases: ExtraOption

A pre-configured --telemetry/--no-telemetry option flag.

Respects the proposed DO_NOT_TRACK environment variable as a unified standard to opt-out of telemetry for TUI/console apps.

The DO_NOT_TRACK convention takes precedence over the user-defined environment variables and the auto-generated values.

The resolved value is stored in ctx.meta[click_extra.context.TELEMETRY], aligning with every other Click Extra option’s per-invocation context-meta storage pattern.

set_telemetry(ctx, param, value)[source]

Store the resolved telemetry opt-in flag on the context’s meta dict.

Reads via click_extra.context.get(ctx, click_extra.context.TELEMETRY). Renamed from save_telemetry to align with the set_<key> convention used by every other ctx.meta-writing callback.

Return type:

None

click_extra.test_plan module

Declarative, black-box CLI test plans.

A test plan is a list of CLITestCase invocations: each runs a target command (a name, a command line, or a path to a binary) once with extra parameters, then checks its exit code and stdout/stderr against literal, substring, or regex expectations. Cases carry their own platform skip/only rules, so one plan runs across operating systems unchanged.

Plans are usually written as YAML and loaded with parse_test_plan(), which needs the optional click-extra[yaml] extra. run_test_plan() drives a list of cases against a target, parallelized per the resolved --jobs count (see click_extra.execution.run_jobs()) and reporting live progress through a click_extra.spinner.Spinner.

This is the black-box, subprocess-level complement to click_extra.testing.CliRunner, which drives a CLI in-process.

exception click_extra.test_plan.SkippedTest[source]

Bases: Exception

Raised when a test case should be skipped.

class click_extra.test_plan.CLITestCase(cli_parameters=<factory>, skip_platforms=<factory>, only_platforms=<factory>, timeout=None, exit_code=None, strip_ansi=False, output_contains=<factory>, stdout_contains=<factory>, stderr_contains=<factory>, output_regex_matches=<factory>, stdout_regex_matches=<factory>, stderr_regex_matches=<factory>, output_regex_fullmatch=None, stdout_regex_fullmatch=None, stderr_regex_fullmatch=None, execution_trace=None)[source]

Bases: object

A single CLI test case: how to invoke the command and what to expect.

Each case runs the command-under-test once with cli_parameters appended, then checks the captured result against the expectation directives below. A case with no expectation only asserts the command ran (plus exit_code, if set).

cli_parameters: tuple[str, ...] | str

Arguments and options appended to the command-under-test.

A plain string is split into arguments (on spaces on Windows, with shlex elsewhere); a list or tuple is used as-is.

skip_platforms: Trait | Group | str | None | Iterable[Trait | Group | str | None | Iterable[_TNestedReferences]]

Platforms (or platform-group IDs) on which to skip this case.

Accepts extra_platforms identifiers such as linux, macos, windows, in any case, mixed freely with group IDs.

only_platforms: Trait | Group | str | None | Iterable[Trait | Group | str | None | Iterable[_TNestedReferences]]

Restrict this case to these platforms; skip it everywhere else.

The mirror image of skip_platforms, using the same identifiers.

timeout: float | str | None = None

Seconds before the command is killed and the case fails as a timeout.

Falls back to the command’s –timeout default, then to no limit.

exit_code: int | str | None = None

Expected process exit code; the case fails on any other code.

strip_ansi: bool = False

Strip ANSI escape sequences from the captured output before matching.

output_contains: tuple[str, ...] | str

Substrings that must all be present in the combined output.

The combined output interleaves stdout and stderr in the order the command wrote them, matching what a user sees in a terminal. The output_* directives are mutually exclusive with the stdout_* / stderr_* ones: a single subprocess run captures either the merged stream or the separate ones, not both.

stdout_contains: tuple[str, ...] | str

Substrings that must all be present in stdout.

stderr_contains: tuple[str, ...] | str

Substrings that must all be present in stderr.

output_regex_matches: tuple[Pattern | str, ...] | str

Regexes that must each match somewhere in the combined output (searched, re.DOTALL). See output_contains for the merged-stream semantics.

stdout_regex_matches: tuple[Pattern | str, ...] | str

Regexes that must each match somewhere in stdout (searched, re.DOTALL).

stderr_regex_matches: tuple[Pattern | str, ...] | str

Regexes that must each match somewhere in stderr (searched, re.DOTALL).

output_regex_fullmatch: Pattern | str | None = None

Regex that must fully match the combined output, line by line. See output_contains for the merged-stream semantics.

stdout_regex_fullmatch: Pattern | str | None = None

Regex that must fully match stdout, line by line.

stderr_regex_fullmatch: Pattern | str | None = None

Regex that must fully match stderr, line by line.

execution_trace: str | None = None

Rendering of the command execution and its output.

Populated after the case runs, for inspection on failure; not a directive you set in a test plan.

property has_merged_output_directives: bool

Whether any output_* directive (merged stream) is set.

property has_separate_stream_directives: bool

Whether any stdout_* or stderr_* directive (separate streams) is set.

run_cli_test(command, additional_skip_platforms, default_timeout)[source]

Run a CLI command and check its output against the test case.

The provided command can be either:

  • a path to a binary or script to execute;

  • a command name to be searched in the PATH,

  • a command line with arguments to be parsed and executed by the shell.

`{todo} Add support for environment variables. `

Return type:

None

click_extra.test_plan.parse_test_plan(plan_string)[source]

Parse a YAML test plan into CLITestCase instances.

The plan must be a YAML list of mappings, each keyed by CLITestCase directive names. Requires the yaml extra.

Raises:
  • ValueError – the plan is empty or a case uses unknown directives.

  • TypeError – the plan is not a list, or a case is not a mapping.

  • ImportError – YAML support is not installed.

Return type:

Generator[CLITestCase, None, None]

click_extra.test_plan.run_test_plan(command, cases, *, jobs=1, select_test=None, skip_platform=None, timeout=None, exit_on_error=False, show_trace_on_error=True, stats=True, show_progress=True)[source]

Run a list of test cases against a target command and tally the results.

Cases are parallelized per jobs (see click_extra.execution.run_jobs()): at one worker they run sequentially and lazily, so exit_on_error can stop before the rest start; otherwise they run in a thread pool and every case runs to completion. Either way outcomes are tallied in submission order. On an interactive terminal a click_extra.spinner.Spinner reports progress unless show_progress is false.

Parameters:
  • command (Path | str) – The target to test: a command name, a command line, or a path to a binary or script.

  • cases (Sequence[CLITestCase]) – The test cases to run.

  • jobs (int) – Number of parallel workers; 1 runs sequentially.

  • select_test (Sequence[int] | None) – 1-based case numbers to run; others are skipped.

  • skip_platform (Trait | Group | str | None | Iterable[Trait | Group | str | None | Iterable[Trait | Group | str | None | Iterable[Trait | Group | str | None | Iterable[_TNestedReferences]]]]) – Extra platforms (or group IDs) to skip every case on.

  • timeout (float | None) – Default per-case timeout in seconds when a case sets none.

  • exit_on_error (bool) – Stop at the first failure (sequential runs only).

  • show_trace_on_error (bool) – Echo the execution trace of each failed case.

  • stats (bool) – Echo a one-line worker summary up front and a result tally.

  • show_progress (bool) – Allow the progress spinner on an interactive terminal.

Return type:

Counter

Returns:

A collections.Counter with total, skipped, and failed keys. A non-zero failed count signals the caller to exit with an error.

click_extra.testing module

CLI testing and simulation of their execution.

click_extra.testing.TNestedArgs

Type for arbitrary nested CLI arguments.

Arguments can be str, pathlib.Path objects or None values.

alias of Iterable[str | Path | None | Iterable[TNestedArgs]]

click_extra.testing.PROMPT = '$ '

Prompt used to simulate the CLI execution.

Hint

Use ASCII characters to avoid issues with Windows terminals.

click_extra.testing.INDENT = '  '

Constants for rendering of CLI execution.

click_extra.testing.OUTPUT_LABEL = '<output>'

Label for the merged stream, where stdout and stderr are interleaved.

click_extra.testing.STDOUT_LABEL = '<stdout>'

Label for the standard output stream.

click_extra.testing.STDERR_LABEL = '<stderr>'

Label for the standard error stream.

click_extra.testing.EXIT_CODE_LABEL = '<exit_code>'

Label for the process exit code.

click_extra.testing.STREAM_FIELDS = {'output_': ('<output>', 'output'), 'stderr_': ('<stderr>', 'stderr'), 'stdout_': ('<stdout>', 'stdout')}

Maps a test-case field prefix to its stream label and StreamView attribute.

output_* directives target the merged stream; stdout_* and stderr_* target the separate streams. Both render_cli_run() and click_extra.test_plan.CLITestCase.run_cli_test() read this single table so the rendered trace and the assertion loop agree on labels and stream selection.

class click_extra.testing.StreamView(stdout='', stderr='', output='', exit_code=None)[source]

Bases: object

Normalized view of a CLI run’s captured streams and exit code.

Both runners produce one of these so the renderer and the assertion loop read a single shape, regardless of whether the run was driven in-process (Click’s click.testing.Result) or as a black-box subprocess (subprocess.CompletedProcess).

A run captures either the merged stream (output) or the separate stdout and stderr streams, never both: the unused fields stay empty.

stdout: str = ''

Captured standard output, or empty when the merged stream was captured.

stderr: str = ''

Captured standard error, or empty when the merged stream was captured.

output: str = ''

Captured merged stream (stdout and stderr interleaved), or empty when the separate streams were captured.

exit_code: int | None = None

Process exit code, or None when unavailable.

classmethod from_result(result)[source]

Build a view from an in-process click.testing.Result.

Click always exposes stdout, stderr and the interleaved output together, so all three are carried over verbatim.

Return type:

StreamView

classmethod from_completed_process(result)[source]

Build a view from a black-box subprocess.CompletedProcess.

A subprocess run with stderr merged into stdout (stderr=STDOUT) reports result.stderr as None: that case is rendered as the interleaved output stream. Otherwise the two streams are kept separate.

Return type:

StreamView

click_extra.testing.args_cleanup(*args)[source]

Flatten recursive iterables, remove all None, and cast each element to strings.

Helps serialize pathlib.Path and other objects.

It also allows for nested iterables and None values as CLI arguments for convenience. We just need to flatten and filters them out.

Return type:

tuple[str, ...]

click_extra.testing.render_cli_run(args, result, env=None)[source]

Generates the full simulation of CLI execution, including output.

Mostly used to print debug traces to user or in test results.

Return type:

str

click_extra.testing.INVOKE_ARGS = {'args', 'catch_exceptions', 'cli', 'color', 'env', 'input', 'self'}

Parameter IDs of click.testing.CliRunner.invoke().

We need to collect them to help us identify which extra parameters passed to invoke() collides with its original signature.

Warning

This has been reported upstream to Click project but has been rejected and not considered an issue worth fixing.

class click_extra.testing.Result(runner, stdout_bytes, stderr_bytes, output_bytes, return_value, exit_code, exception, exc_info=None)[source]

Bases: Result

A Result subclass with automatic traceback formatting.

Enhances __repr__ so that pytest assertion failures show the full traceback instead of just the exception type.

property formatted_exception: str | None[source]

Full formatted traceback, or None if no exception occurred.

class click_extra.testing.CliRunner(charset='utf-8', env=None, echo_stdin=False, catch_exceptions=True, capture='sys')[source]

Bases: CliRunner

Augment click.testing.CliRunner with extra features and bug fixes.

force_color: bool = False

Global class attribute to override the color parameter in invoke.

invoke(cli, *args, input=None, env=None, catch_exceptions=True, color=None, **extra)[source]

Same as click.testing.CliRunner.invoke() with extra features.

  • The first positional parameter is the CLI to invoke. The remaining positional parameters of the function are the CLI arguments. All other parameters are required to be named.

  • The CLI arguments can be nested iterables of arbitrary depth. This is useful for argument composition of test cases with @pytest.mark.parametrize.

  • Allow forcing of the color property at the class-level via force_color attribute.

  • Adds a special case in the form of color="forced" parameter, which allows colored output to be kept, while forcing the initialization of Context.color = True. This is not allowed in current implementation of click.testing.CliRunner.invoke() because of colliding parameters.

  • Strips all ANSI codes from results if color was explicirely set to False.

  • Always prints a simulation of the CLI execution as the user would see it in its terminal. Including colors.

  • Pretty-prints a formatted exception traceback if the command fails.

Parameters:
  • cli (Command) – CLI to invoke.

  • args (str | Path | None | Iterable[str | Path | None | Iterable[Iterable[str | Path | None | Iterable[TNestedArgs]]]]) – can be nested iterables composed of str, pathlib.Path objects and None values. The nested structure will be flattened and None values will be filtered out. Then all elements will be casted to str. See args_cleanup() for details.

  • input (str | bytes | IO | None) – same as click.testing.CliRunner.invoke().

  • env (Mapping[str, str | None] | None) – same as click.testing.CliRunner.invoke().

  • catch_exceptions (bool) – same as click.testing.CliRunner.invoke().

  • color (bool | Literal['forced'] | None) – If a boolean, the parameter will be passed as-is to click.testing.CliRunner.isolation(). If "forced", the parameter will be passed as True to click.testing.CliRunner.isolation() and an extra color=True parameter will be passed to the invoked CLI.

  • extra (Any) – same as click.testing.CliRunner.invoke(), but colliding parameters are allowed and properly passed on to the invoked CLI.

Return type:

Result

click_extra.testing.unescape_regex(text)[source]

De-obfuscate a regex for better readability.

This is like the reverse of re.escape().

Return type:

str

exception click_extra.testing.RegexLineMismatch(regex_line, content_line, line_number)[source]

Bases: AssertionError

Raised when a regex line does not match the corresponding content line.

click_extra.testing.REGEX_NEWLINE = '\\n'

Newline token used to split a multi-line regex pattern for line-by-line matching.

click_extra.testing.regex_fullmatch_line_by_line(regex, content)[source]

Check that the content matches the given regex.

If the regex does not fully match the content, raise an AssertionError, with a message showing the first mismatching line.

This is useful when comparing large walls of text, such as CLI output.

Return type:

None

click_extra.theme_docs module

Render a theme palette as an inline-styled HTML fragment for documentation.

palette_html() is called from docs/theme.md to render every built-in theme’s palette at Sphinx build time. inject_slot_example_docstring() is registered as a Sphinx autodoc-process-docstring hook from docs/conf.py to inject a colored example into each HelpTheme slot’s autodoc block. This is build-time documentation code, kept out of the runtime theme module.

click_extra.theme_docs.inject_slot_example_docstring(app, what, name, obj, options, lines)[source]

Sphinx autodoc-process-docstring hook injecting per-slot colored examples.

For every HelpTheme slot that has an entry in _PALETTE_EXAMPLES, append an ansi-color code block to the slot’s autodoc lines. The example is rendered through _render_slot_ansi, which calls BUILTIN_THEMES["dark"].<slot>(text) to obtain the actual ANSI escapes click-extra would emit at runtime.

Wire this up from a Sphinx conf.py with:

from click_extra.theme_docs import inject_slot_example_docstring


def setup(app):
    app.connect("autodoc-process-docstring", inject_slot_example_docstring)

The hook intentionally targets only click_extra.theme.HelpTheme.<slot> names so it won’t accidentally rewrite unrelated docstrings; downstream projects can register the hook in their own conf.py if they consume HelpTheme docstrings.

Return type:

None

click_extra.theme_docs.palette_html(theme)[source]

Render a theme’s palette as an inline-styled HTML <dl> fragment.

The output is a two-column definition list (slot name → styled swatch plus attribute decorations) safe to inject into MyST or reST host documents via the python:render Sphinx directive (or any raw:: html block). Used by docs/theme.md to render every built-in theme’s palette at Sphinx build time without hand-maintaining swatch tables. Downstream projects with their own custom themes can call the same helper to get matching swatch listings in their own docs:

```{python:render}
from click_extra.theme_docs import palette_html
from my_app.themes import MY_THEME
print(palette_html(MY_THEME))
```

Slots that hold identity (no styling applied), the boolean cross_ref_highlight toggle, the internal _style_kwargs cache, and a handful of inherited cloup slots that built-ins never style are skipped: every emitted row corresponds to a real palette choice in the theme.

Return type:

str

click_extra.types module

Custom click.ParamType subclasses for multi-pick and Enum choices.

class click_extra.types.MultiChoice(choices=(), separator=',', case_sensitive=True)[source]

Bases: ParamType

Comma-separated multi-pick from a fixed set of values.

The pick-many counterpart to click.Choice. Accepts a single token containing several values joined by a configurable separator (defaults to ,), parses it into a tuple[str, ...] and validates each value against choices when that set is non-empty.

The rendered metavar is [a,b,c] (separator-joined, parallel to Choice’s [a|b|c]): click_extra.highlight._HelpColorsMixin auto-detects the separator and highlights each individual value the same way it does for Choice.

Note

Click does not ship a built-in equivalent. The closest idiomatic approach is click.Choice([...]) + multiple=True, which requires the flag to be repeated (--tag a --tag b --tag c) rather than comma-separated. The lack of a single-token, separator-based variant upstream has been raised in:

  • pallets/click#2771 (open): request for nargs=-1 with a non-whitespace separator, covering exactly this use case.

  • pallets/click#2537 (closed as not planned): earlier request for space-separated multi values via nargs=-1 on options.

Maintainers have leaned on the orthogonality argument: multiple=True already exists, separator conventions vary across communities (, vs. : vs. ;), and escaping breaks down when a value contains the chosen separator. MultiChoice ships the convention anyway because SQL-style SELECT a, b, c syntax reads more naturally for the tabular use cases click-extra supports (click_extra.table.ColumnsOption is the headline consumer).

Initialize the type.

Parameters:
  • choices (Sequence[str]) – the accepted values. When non-empty, convert() rejects unknown tokens with fail. When empty, the type behaves as a pure separator-aware parser and leaves validation to the consumer.

  • separator (str) – the token boundary. Use any single character; this also drives the metavar rendering ([a<sep>b<sep>c]).

  • case_sensitive (bool) – when False, tokens match choices case-insensitively and the returned tuple holds the canonical (original-case) values from choices.

name: str = 'multi'

the descriptive name of this type

choices: tuple[str, ...]
separator: str
case_sensitive: bool
get_metavar(param, ctx=None)[source]

Render [a<sep>b<sep>c] when choices is set, None otherwise.

None falls back to Click’s default rendering (the uppercased name, like MULTI).

convert(value, param, ctx)[source]

Split value on separator and validate each token.

Already-parsed tuples and lists are returned unchanged so defaults declared as tuples flow through untouched. Empty tokens (consecutive separators, trailing separator) are dropped silently.

Return type:

tuple[str, ...]

class click_extra.types.ChoiceSource(*values)[source]

Bases: Enum

Source of choices for EnumChoice.

KEY = 'key'
NAME = 'name'
VALUE = 'value'
STR = 'str'
class click_extra.types.EnumChoice(choices, case_sensitive=False, choice_source=ChoiceSource.STR, show_aliases=False)[source]

Bases: Choice

Choice type for Enum.

Allows to select which part of the members to use as choice strings, by setting the choice_source parameter to one of:

  • ChoiceSource.KEY or ChoiceSource.NAME to use the key (the name property),

  • ChoiceSource.VALUE to use the value,

  • ChoiceSource.STR to use the str() string representation, or

  • A custom callable that takes an Enum member and returns a string.

Defaults to ChoiceSource.STR, which only requires you to define the __str__() method on your Enum to produce beautiful choice strings.

Same as click.Choice, but takes an Enum as choices.

Also defaults to case-insensitive matching.

choices: tuple[str, ...]

The strings available as choice.

Hint

Contrary to the parent Choice class, we store choices directly as strings, not the Enum members themselves. That way there is no surprises when displaying them to the user.

This trick bypass Enum-specific code path in the Click library. Because, after all, a terminal environment only deals with strings: arguments, parameters, parsing, help messages, environment variables, etc.

get_choice_string(member)[source]

Derive the choice string from the given Enum’s member.

Return type:

str

normalize_choice(choice, ctx)[source]

Expand the parent’s normalize_choice() to accept Enum members as input.

Parent method expects a string, but here we allow passing Enum members too.

Return type:

str

convert(value, param, ctx)[source]

Convert the input value to the corresponding Enum member.

The parent’s convert() is going to return the choice string, which we then map back to the corresponding Enum member.

Return type:

Enum

click_extra.version module

Introspect CLI metadata at runtime and print a colored --version string.

VersionOption gathers the executed CLI’s metadata (module and package names, distribution version, author and license, environment profile, and the live Git state) and renders them through a customizable, colorized message template.

Git fields (git_branch, git_short_hash, …) are resolved at runtime by shelling out to git, with two fallbacks for git-less environments: a pre-baked __<field>__ dunder in the CLI module (injected before build by click_extra.prebake), then a committed .git_archival.json populated by git archive.

click_extra.version.GIT_FIELDS: dict[str, tuple[str, ...]] = {'git_branch': ('rev-parse', '--abbrev-ref', 'HEAD'), 'git_date': ('show', '-s', '--format=%ci', 'HEAD'), 'git_long_hash': ('rev-parse', 'HEAD'), 'git_short_hash': ('rev-parse', '--short', 'HEAD'), 'git_tag': ('describe', '--tags', '--exact-match', 'HEAD')}

Git fields whose live value is the stripped output of one static git subcommand, mapped to that subcommand’s args.

git_tag_sha, git_distance and git_dirty are excluded: their resolution is not a single static git invocation whose stripped output is the value. git_tag_sha dereferences the tag (git rev-list -1 <tag>), git_distance parses git describe and git_dirty maps the porcelain status to a label. See resolve_git_tag_sha(), resolve_git_distance() and resolve_git_dirty().

For the resolver of every pre-bakeable git field (these five plus the three computed ones), keyed uniformly by field ID, see GIT_RESOLVERS.

click_extra.version.run_git(*args, cwd=None, allow_empty=False)[source]

Run a git command and return its stripped output, or None.

cwd defaults to the current working directory when not provided.

By default an empty output is collapsed to None (treated like a failure). Set allow_empty to keep an empty string instead, which some commands use meaningfully: git status --porcelain prints nothing for a clean work tree, and that is distinct from the command failing.

Return type:

str | None

click_extra.version.resolve_git_dirty(cwd=None)[source]

Report the work-tree state as "dirty", "clean" or None.

Returns "dirty" when git status --porcelain reports uncommitted changes, "clean" when it reports none, and None when the state cannot be determined (not a Git repository, or git is unavailable).

The empty output of a clean work tree is meaningful here, so the command is run with allow_empty to tell it apart from a failure.

Return type:

str | None

click_extra.version.resolve_git_distance(cwd=None)[source]

Count commits since the most recent tag, as a string, or None.

Parses git describe --tags --long, whose output has the form <tag>-<distance>-g<short_hash>. Returns None when no tag is reachable, the directory is not a Git repository, or git is unavailable.

Return type:

str | None

click_extra.version.resolve_git_tag_sha(cwd=None)[source]

Resolve the commit SHA the tag at HEAD points at, or None.

Runs git describe --tags --exact-match HEAD to find the tag, then git rev-list -1 <tag> to dereference it to a commit SHA. Returns None when HEAD is not at a tagged commit, the directory is not a Git repository, or git is unavailable.

Return type:

str | None

click_extra.version.GIT_RESOLVERS: dict[str, Callable[[Path | None], str | None]] = {'git_branch': <function _direct_git_resolver.<locals>.resolver>, 'git_date': <function _direct_git_resolver.<locals>.resolver>, 'git_dirty': <function resolve_git_dirty>, 'git_distance': <function resolve_git_distance>, 'git_long_hash': <function _direct_git_resolver.<locals>.resolver>, 'git_short_hash': <function _direct_git_resolver.<locals>.resolver>, 'git_tag': <function _direct_git_resolver.<locals>.resolver>, 'git_tag_sha': <function resolve_git_tag_sha>}

Canonical live resolver for every pre-bakeable git_* field.

Maps each field ID to a callable that takes an optional working directory and returns the field’s value by shelling out to git (or None when it cannot be resolved). This is the single source of truth for how each git field is computed live, shared by two consumers:

  • VersionOption’s runtime accessors, which wrap each resolver with the pre-baked-dunder and .git_archival.json fallbacks.

  • the click-extra prebake all command, which calls every resolver to bake values into source files at build time.

Keeping it here means adding a new git field is a one-line edit in this module, with no matching change needed in the CLI.

click_extra.version.find_archival_file(start)[source]

Walk up from start to find a .git_archival.json file.

Returns the first match in start or any of its parents, or None.

Return type:

Path | None

click_extra.version.read_archival(path)[source]

Parse a .git_archival.json file into a string mapping.

Returns an empty mapping when the file is missing, unreadable, or not a valid JSON object.

Return type:

dict[str, str]

click_extra.version.archival_field(data, field_id)[source]

Resolve a git_* field from parsed .git_archival.json data.

data follows the setuptools-scm archival schema: node (full hash), node-date, describe-name and ref-names. The same file is read by setuptools-scm and Dunamai, so a single committed .git_archival.json serves all three.

Returns None when the field is absent, empty, or still holds an unsubstituted $Format:…$ placeholder. That last case is what a plain checkout contains: git archive performs the substitution, so values are real only inside an exported archive (including GitHub’s source tarballs).

There is no entry for git_dirty: an archive has no work tree, so its state is unknowable.

Return type:

str | None

click_extra.version.resolve_distribution(names)[source]

Return the first installed distribution among names, or None.

Probes each candidate name in order with importlib.metadata.distribution() and returns the first that resolves to an installed distribution. Used to pick a distribution from a set of plausible spellings (for example the program name with - / _ variants) before reading its metadata.

Return type:

str | None

click_extra.version.meta_value(meta, *keys)[source]

Return the first non-empty value among core-metadata keys.

Accessed through in + [] (rather than .get()) to dodge the deprecated implicit-None return on missing keys.

Return type:

str | None

click_extra.version.resolve_author(meta)[source]

Return the author(s) from meta’s core metadata, or None.

Prefers the Author field, then the Maintainer field, then the display name parsed out of the Author-email / Maintainer-email fields (Name <email>). Returns None when meta is None or no author can be determined.

Return type:

str | None

click_extra.version.resolve_license(meta)[source]

Return the license from meta’s core metadata, or None.

Prefers the SPDX License-Expression field (core metadata 2.4+). Falls back to the human-readable name of the first License :: trove classifier, then to the free-form License field (which may hold the full license text). Returns None when meta is None or no license can be determined.

Return type:

str | None

class click_extra.version.VersionOption(param_decls=None, message=None, fields=None, styles=None, message_style=None, is_flag=True, expose_value=False, is_eager=True, help='Show the version and exit.', **kwargs)[source]

Bases: ExtraOption

Gather CLI metadata and prints a colored version string.

Note

This started as a copy of the standard @click.version_option() decorator, but is no longer a drop-in replacement. Hence the Extra prefix.

This address the following Click issues:

  • click#2324, to allow its use with the declarative params= argument.

  • click#2331, by distinguishing the module from the package.

  • click#1756, by allowing path and Python version.

Preconfigured as a --version option flag.

Parameters:
  • message (str | None) – the message template to print, in format string syntax. Defaults to {prog_name}, version {version}.

  • fields (Mapping[str, Any] | None) – mapping of template field name to a forced value, overriding the value auto-computed for that field. Keys must be members of template_fields (for example {"version": "1.2.3"}).

  • styles (Mapping[str, Callable[[str], str] | None] | None) – mapping of template field name to its Style, merged over default_styles. Pass None as a value to clear a field’s default style. Keys must be members of template_fields.

  • message_style (Callable[[str], str] | None) – fallback style for the message literals and for any field that has no style of its own.

template_fields: tuple[str, ...] = ('module', 'module_name', 'module_file', 'module_version', 'package_name', 'package_version', 'author', 'license', 'exec_name', 'version', 'git_repo_path', 'git_branch', 'git_long_hash', 'git_short_hash', 'git_date', 'git_tag', 'git_tag_sha', 'git_distance', 'git_dirty', 'prog_name', 'env_info')

List of field IDs recognized by the message template.

default_styles: ClassVar[dict[str, Callable[[str], str]]] = {'env_info': Style(fg='bright_black'), 'exec_name': Style(fg='bright_white', bold), 'git_branch': Style(fg='cyan'), 'git_date': Style(fg='bright_black'), 'git_dirty': Style(fg='red'), 'git_distance': Style(fg='green'), 'git_long_hash': Style(fg='yellow'), 'git_repo_path': Style(fg='bright_black'), 'git_short_hash': Style(fg='yellow'), 'git_tag': Style(fg='cyan'), 'git_tag_sha': Style(fg='yellow'), 'module_name': Style(fg='bright_white', bold), 'module_version': Style(fg='green'), 'package_name': Style(fg='bright_white', bold), 'package_version': Style(fg='green'), 'prog_name': Style(fg='bright_white', bold), 'version': Style(fg='green')}

Default style for each template field.

Fields absent from this mapping render with no style of their own and fall back to message_style (or no color when that is unset). User-provided styles are merged over these defaults.

message: str = '{prog_name}, version {version}'

Default message template used to render the version string.

styles: dict[str, Callable[[str], str] | None]
static cli_frame()[source]

Returns the frame in which the CLI is implemented.

Inspects the execution stack frames to find the package in which the user’s CLI is implemented.

Returns the frame itself.

Return type:

FrameType

property module: ModuleType[source]

Returns the module in which the CLI resides.

property module_name: str[source]

Returns the full module name or __main__.

property module_file: str | None[source]

Returns the module’s file full path.

property module_version: str | None[source]

Returns the string found in the local __version__ variable.

Hint

__version__ is an old pattern from early Python packaging. It is not a standard variable and is not defined in the packaging PEPs.

You should prefer using the package_version property below instead, which uses the standard library importlib.metadata API.

We’re still supporting it for backward compatibility with existing codebases, as Click removed it in version 8.2.0.

property package_name: str | None[source]

Returns the package name.

property package_version: str | None[source]

Returns the package version if installed.

Resolved from the distribution name (see _distribution_name) via importlib.metadata.version(). Returns None if the package is not installed or cannot be resolved.

property author: str | None[source]

Returns the package author(s) from its core metadata.

Delegates to resolve_author(): prefers the Author field, then the Maintainer field, then the display name parsed out of the Author-email / Maintainer-email fields (Name <email>). Returns None if no author can be determined.

property license: str | None[source]

Returns the package license from its core metadata.

Delegates to resolve_license(): prefers the SPDX License-Expression field, falls back to the human-readable name of the first License :: trove classifier, then to the free-form License field. Returns None if no license can be determined.

property exec_name: str[source]

User-friendly name of the executed CLI.

Returns the module name. But if the later is __main__, returns the package name.

If not packaged, the CLI is assumed to be a simple standalone script, and the returned name is the script’s file name (including its extension).

property version: str | None[source]

Return the version of the CLI.

Returns the module version if a __version__ variable is set alongside the CLI in its module.

Else returns the package version if the CLI is implemented in a package, using importlib.metadata.version().

For development versions (containing .dev), automatically appends the Git short hash as a PEP 440 local version identifier, producing versions like 1.2.3.dev0+abc1234. This helps identify the exact commit a dev build was produced from. If Git is unavailable, the plain dev version is returned.

Versions that already contain a + (a pre-baked local version identifier, typically set at build time by CI pipelines) are returned as-is to avoid producing invalid double-suffixed versions like 1.2.3.dev0+abc1234+xyz5678.

property git_repo_path: Path | None[source]

Find the Git repository root directory.

property git_branch: str | None[source]

Returns the current Git branch name.

Checks for a pre-baked __git_branch__ dunder first, then git rev-parse --abbrev-ref HEAD, then .git_archival.json.

property git_long_hash: str | None[source]

Returns the full Git commit hash.

Checks for a pre-baked __git_long_hash__ dunder first, then git rev-parse HEAD, then .git_archival.json.

property git_short_hash: str | None[source]

Returns the short Git commit hash.

Checks for a pre-baked __git_short_hash__ dunder first, then git rev-parse --short HEAD, then .git_archival.json (where it is derived from the first 7 characters of the full hash).

Hint

The short hash is usually the first 7 characters of the full hash, but this is not guaranteed to be the case.

But it is at least guaranteed to be unique within the repository, and a minimum of 4 characters.

property git_date: str | None[source]

Returns the commit date in ISO format: YYYY-MM-DD HH:MM:SS +ZZZZ.

Checks for a pre-baked __git_date__ dunder first, then git show -s --format=%ci HEAD, then .git_archival.json (whose node-date is strict ISO 8601, like 2021-01-01T12:00:00+00:00).

property git_tag: str | None[source]

Returns the Git tag pointing at HEAD, if any.

Checks for a pre-baked __git_tag__ dunder first, then git describe --tags --exact-match HEAD, then .git_archival.json.

Returns None if HEAD is not at a tagged commit.

property git_tag_sha: str | None[source]

Returns the commit SHA that the current tag points at.

Checks for a pre-baked __git_tag_sha__ dunder first, then git rev-list -1 on the tag returned by git_tag, then .git_archival.json. Returns None if HEAD is not at a tag.

property git_distance: str | None[source]

Number of commits since the most recent tag, or None.

Checks for a pre-baked __git_distance__ dunder first, then parses git describe --tags --long, then falls back to .git_archival.json. None when no tag is reachable or Git is unavailable.

property git_dirty: str | None[source]

Work-tree state: "dirty", "clean" or None.

Checks for a pre-baked __git_dirty__ dunder first, then runs git status --porcelain. None when not in a Git repository or Git is unavailable. There is no .git_archival.json fallback: an archive has no work tree, so its state is unknowable.

property prog_name: str | None[source]

Return the name of the CLI, from Click’s point of view.

Get the info_name of the root command.

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

Various environment info.

Returns the data produced by boltons.ecoutils.get_profile().

colored_template(template=None)[source]

Insert ANSI styles to a message template.

Accepts a custom template as parameter, otherwise uses the default message defined on the Option instance.

This step is necessary because we need to linearize the template to apply the ANSI codes on the string segments. This is a consequence of the nature of ANSI, directives which cannot be encapsulated within another (unlike markup tags like HTML).

Return type:

str

render_message(template=None)[source]

Render the version string from the provided template.

Accepts a custom template as parameter, otherwise uses the default self.colored_template() produced by the instance.

Return type:

str

print_debug_message()[source]

Render in debug logs all template fields in color.

Todo

Pretty print JSON output (easier to read in bug reports)?

Return type:

None

print_and_exit(ctx, param, value)[source]

Print the version string and exits.

Also stores all version string elements in the Context’s meta dict.

Return type:

None