click_extra.config.option module¶
classDiagram
ChainMap <|-- _DeepChainMap
ConfigDiscovery <|-- ConfigOption
Enum <|-- Sentinel
ExtraOption <|-- ConfigOption
ExtraOption <|-- NoConfigOption
ExtraOption <|-- ValidateConfigOption
ParamStructure <|-- ConfigOption
ValueError <|-- _EmptyConfigError
Utilities to load parameters and options from a configuration file.
Hint
The whole namespace designates configuration files by the short name config:
not conf, cfg, configuration or settings. In the context of a CLI,
config reads as nothing else.
Dotted keys in configuration files (like "subcommand.option": value) are
automatically expanded into nested dicts before merging, so users can freely mix
flat dot-notation and nested structures in any supported format.
- click_extra.config.option.get_app_dir(app_name, roaming=True, force_posix=False)¶
click.get_app_dir()’s Unix branch, taken on every platform.Returns an expanded path like the original, since a caller resolves it before Click Extra shrinks the home prefix back to
~for display.XDG_CONFIG_HOMEis deliberately ignored: honoring it would put the host back into the rendered output.
- click_extra.config.option.CONFIG_OPTION_NAME = 'config'¶
Hardcoded name of the configuration option.
The
--configand--no-configoptions share this name, so they compete with each other to either set a path pattern or disable the use of any configuration file at all.
- click_extra.config.option.DEFAULT_EXCLUDED_PARAMS = ('config', 'export_config', 'params', 'validate_config', 'version')¶
Default parameter IDs to exclude from the configuration file.
Defaults to:
--configoption, which cannot be used to recursively load another configuration file.--export-configflag, which like--paramsintrospects the CLI and exits, so it has no place in the configuration it would export.--paramsflag, which is like--helpand stops the CLI execution.--validate-configoption, which belongs to the same self-referential config machinery as--configand--export-config.--version, which is not a configurable option per-se.
--helpis excluded too (it makes no sense to have a configuration file always force a CLI to show the help and exit), but is deliberately absent from this tuple: unlike the entries above, click-extra does not control that option’s internal name. It is resolved at runtime instead, inConfigOption.excluded_params, so a rename on Click’s own side does not silently stop excluding it.
- click_extra.config.option.THEMES_CONFIG_KEY: str = 'themes'¶
Sub-key under
[tool.<cli>]where user-defined themes live in config.Used by
ConfigOptionto find[tool.<cli>.themes.<name>]tables, build them viaHelpTheme.from_dict, and stash the result onctx.meta[click_extra.context.THEME_OVERRIDES]. The constant is the single source of truth shared by_builtin_config_validators,ConfigOption._apply_theme_overrides, andclick_extra.theme.themes_from_config().
- class click_extra.config.option.Sentinel(*values)[source]¶
Bases:
EnumEnum used to define sentinel values.
Note
This reuses the pattern of
click._utils.Sentinel.See also
- NO_CONFIG = <object object>¶
- VCS = <object object>¶
- click_extra.config.option.NO_CONFIG = Sentinel.NO_CONFIG¶
Sentinel used to indicate that no configuration file must be used at all.
- click_extra.config.option.VCS = Sentinel.VCS¶
Sentinel used to stop parent directory walking at the nearest VCS root.
- class click_extra.config.option.ConfigOption(param_decls=None, *, metavar='LOCATION', 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=None, show_file_patterns=None, roaming=True, force_posix=False, search_pattern_flags=None, search_parents=False, stop_at=Sentinel.VCS, cascade=False, excluded_params=None, included_params=None, strict=False, config_schema=None, schema_strict=False, fallback_sections=(), config_validators=(), **kwargs)[source]¶
Bases:
ConfigDiscovery,ExtraOption,ParamStructureA pre-configured option adding
--config LOCATION.Caution
The first
ConfigOptiona process builds replacesclick.Group.parse_argsfor all of it. The replacement is how the subcommands the configuration names still run in the two cases the option never sees, on a group class click-extra does not own. One is a bare invocation, for which Click prints itsno_args_is_helpscreen before it runs any parameter. The other is a subgroup, which holds no option of its own. Every other call goes to Click unchanged, as does each group of a CLI carrying noConfigOption.Takes as input a path to a file or folder, a glob pattern, or an URL.
is_eageris active by default so thecallbackgets the opportunity to set thedefault_mapof the CLI before any other parameter is processed.defaultis set to the value returned byself.default_pattern(), which is a pattern combining the default configuration folder for the CLI (as returned byclick.get_app_dir()) and all supported file formats.Attention
Default search pattern must follow the syntax of wcmatch.glob.
excluded_paramsare 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--params. Will default to the value ofDEFAULT_EXCLUDED_PARAMS, plus the CLI’s--helpoption, resolved at runtime.included_paramsis the inverse ofexcluded_params: only the listed parameters will be loaded from the configuration file. Cannot be used together withexcluded_params.
- file_format_patterns: dict[ConfigFormat, tuple[str, ...]]¶
Mapping of
ConfigFormatto 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.
- auto_file_formats¶
Whether the format set was inherited instead of chosen by the developer.
Truewhen nofile_format_patternswas provided, so the set is whatever the installed extra dependencies enable. It ranges from 3 patterns on a bare install to 14 with every extra, which is an artifact of the environment rather than a decision the CLI made.Only
collapse_default()reads it, and only whenshow_file_patternsis left atNone.
- show_file_patterns¶
Whether the help screen prints the file patterns of the default.
Follows the tri-state convention of Click Extra’s other display settings:
Noneprints them when the developer chose the format set, and hides them when it was inherited from the install.Truealways prints them, which is how a CLI advertises the formats its own dependencies enable.Falsealways hides them.
See
collapse_default()for what each state renders.
- force_posix¶
Configuration for default folder search.
roamingandforce_posixare fed to click.get_app_dir() to determine the location of the default configuration folder.
- search_parents: bool¶
Indicates whether to walk back the tree of parent folders when searching for configuration files.
- stop_at: Path | str | Literal[Sentinel.VCS] | None¶
Boundary for parent directory walking.
None: walk up to filesystem root.VCS: stop at the nearest VCS root, whichever system marks it (seeVCS_DIRS) (default).A
Pathorstr: stop at that directory.
- cascade¶
Merge every discovered configuration file instead of stopping at the first parseable one.
When
True, all files found by auto-discovery (the app-dir search, including the parent walk whensearch_parents=True, plus thepyproject.tomlCWD search when enabled) are loaded and layered into the context’sdefault_map. The most local file wins each key, in the sections of subcommands too: apyproject.tomlfound near the CWD overrides the app-dir config, which overrides files found higher up the parent walk. A list comes whole from the most local file setting it.An explicit
--configvalue never cascades: it pins a single source, whatever the pattern matches.Defaults to
False: the first successfully parsed file wins.
- extra_excluded_params: frozenset[str]¶
Additional exclusions merged into the dynamic
excluded_paramsdefault.Populated by
Command’sexcluded_paramsforwarding, which is additive: the default blocklist (--config,--version,--help, …) is preserved and the forwarded IDs are unioned into it when the property resolves. Ignored when an explicitexcluded_paramswas frozen on the instance, as the property is then never consulted.
- included_params: frozenset[str] | None¶
Allowlist of parameter IDs, mutually exclusive with
excluded_params.Nonedisables the allowlist. Otherwisebuild_param_trees()walks only the subcommands an allowed ID lies under, and resolves the parameters it reaches intoexcluded_params.
- 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 (likesub_section_key).Any callable
dict → T: called directly with the raw dict. Works with Pydantic’sModel.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 viaget_tool_config.
- schema_strict¶
Strictness for schema validation (separate from
strict).If
True, raiseValueErrorwhen the config section contains keys that do not match any dataclass field (after normalization and flattening). Only applies whenconfig_schemais a dataclass.If
False, ignore unrecognized keys. When the section is schema-only (included_params=()), a warning still names them: seewarn_unknowninmake_schema_callable().
Note
This is distinct from
strict, which controls whether config keys not matching CLI parameters are rejected.schema_strictvalidates 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.
- schema_warn_unknown: bool¶
Warn on config keys unknown to the schema, in lax mode.
Inferred, not user-supplied: an explicitly empty
included_paramsmeans no CLI parameter is merged from the app’s config section, so the section is schema-only and any key the schema does not know is a typo worth a warning. Forwarded tomake_schema_callable()and the validation pipeline aswarn_unknown.
- config_validators: tuple[ConfigValidator, ...]¶
Extension validators for sub-trees of the configuration file.
Each
ConfigValidatortargets a dottedextension_pathrelative 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 (the one for
[tool.<cli>.themes.<name>]tables, seeclick_extra.theme.validate_themes_config()); user-supplied validators are appended after them. App code that registers its own validator on the sameextension_pathruns alongside the built-in: both validators are called, both sets of errors surface.
- apply_command_settings(*, config_schema=None, config_strict=False, schema_strict=False, fallback_sections=(), config_validators=(), included_params=None, excluded_params=None, cascade=False)[source]¶
Take over the configuration settings a command was built with.
Commandaccepts the settings of its default--configoption as keyword arguments of its own, so a CLI tunes that option without replacing the whole default parameter list, and hands them over here once its parameters are known. Each argument defaults to the value meaning “leave the option as it is”.excluded_paramsis additive, where the option’s own argument replaces the default blocklist: the forwarded IDs join it, throughextra_excluded_paramswhile the blocklist is still the dynamic default, and straight into the frozen value otherwise. Theconfig_validatorsjoin click-extra’s built-in ones the same way, as they do when passed to the option itself.- Raises:
ValueError – when
excluded_paramsis forwarded to an option carrying its ownincluded_params, the two filters being mutually exclusive.- Return type:
- property file_pattern_flags: int[source]¶
Flags provided to all calls of
wcmatch.fnmatch.Applies to the matching of file names against supported format patterns specified in
file_format_patterns.Noneat construction picksNEGATE | SPLIT.Important
The
SPLITflag is always forced, as our multi-pattern design relies on it.Resolved on first use rather than in
__init__, so building the option imports nothing from wcmatch.
- property search_pattern_flags: int[source]¶
Flags provided to all calls of
wcmatch.glob.Applies to both the default pattern and any user-provided pattern.
Noneat construction picks GLOBSTAR | FOLLOW | DOTGLOB | BRACE | SPLIT | GLOBTILDE | NODIR.Important
The
BRACEflag is always forced, so that multi-format default patterns using{pat1,pat2,...}syntax expand correctly.The
NODIRflag is always forced, to optimize the search for files only.Resolved on first use rather than in
__init__, so building the option imports nothing from wcmatch.
- property excluded_params: frozenset[str][source]¶
Generates the default list of fully-qualified IDs to exclude.
Danger
Resolved once, on first read, and only when the user did not provide a list of their own.
The IDs are rooted at the CLI name, which only the running context knows: hence a property, read within that context, rather than a value set by the constructor.
- property file_pattern: str[source]¶
Compile all file patterns from the supported formats.
Uses
,(comma) notation to combine multiple patterns, suitable forwcmatchbrace expansion ({pat1,pat2,...}).Returns a single pattern string.
- default_pattern()[source]¶
Returns the default pattern used to search for the configuration file.
Defaults to the patterns of every format in
file_format_patterns, under<app_dir>:<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 theroamingandforce_posixproperties.Multiple file format patterns are wrapped with
{…}brace-expansion syntax so thatwcmatch.globcorrectly applies the directory prefix to every sub-pattern.Note
A CLI wanting another folder layout, like the one platformdirs computes, passes its own pattern to
defaultinstead. That keeps the layout a choice of the CLI rather than a dependency of this package: see the documentation.- Return type:
- 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
GLOBTILDEflag is set insearch_pattern_flags.An inherited format set is then reduced to the folder it searches, as described in
collapse_default().- Return type:
OptionHelpExtra
- render_default(ctx)[source]¶
The default search pattern, as a portable home-relative path.
Keeps the whole pattern, file patterns included. The help screen collapses an inherited set on top of this with
collapse_default(), but a consumer with room for the files (theFILESsection of a man page) calls this method instead. A URL is returned as given.- Return type:
- collapse_default(default)[source]¶
Reduce an inherited default pattern to the folder it searches.
A CLI installed with every extra searches 15 file patterns, so its default renders as a 136-character glob. The help screen has no space for it and no place to break it, so Click splits it mid-word:
[default: ~/.config/hello/{*. toml,*.yaml,*.yml,*.json,*.json5,*.jwcc,*.jsonc, *.hjson,*.ini,*.xml,*.plist,*.sqlite,*.sqlite3,* .conf,pyproject.toml}]Rendering the folder alone answers the question a reader opens
--helpfor, on one line, and keeps the answer the same on every install:[default: ~/.config/hello/]
A developer who passed
file_format_patternschose that set, so it is displayed in full: the pattern is short enough to read, and the help screen is where the choice shows up.show_file_patternsoverrides that reading in either direction, andTrueis what a CLI advertising its formats wants: the set is computed from the installed dependencies at each invocation, so the help screen reports what that install can really parse. The complete pattern of any CLI stays available in the output of--params.The trailing separator marks the value as a folder, since it is a search base and not a location the option accepts back.
- Return type:
- parse_conf(content, formats, location=None)[source]¶
Parse the
contentwith the givenformats.Tries to parse the given raw
contentstring with each of the givenformats, in order. Yields the resulting data structure for each successful parse.locationis the path thecontentwas read from. It is only needed by formats that cannot be parsed from a text payload, likeSQLITE, which is read straight from its file, and the binary variant ofPLIST, which only exists on disk. Such formats are skipped whenlocationis missing or is not a local file.Attention
Formats whose parsing raises an exception or does not return a
dictare considered a failure and are skipped. A format parsing the content toNone, as YAML does for a document of comments only, yields an emptydictinstead.This follows the parse, don’t validate principle.
- read_and_parse_all_conf(pattern)[source]¶
Search for every parseable configuration file matching
pattern.Yields
(location, parsed_conf)pairs in discovery order, which is the most local first: the original search location, then each parent directory when parent search is enabled. Files already yielded (as matched by their resolved location) are skipped, as are files that parse to an empty configuration.Raises
FileNotFoundErrorif no file at all matched the pattern.
- 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, or a character device or a named pipe that
patternnames,is not empty,
match file format patterns,
can be parsed successfully, and
produce a non-empty data structure.
Raises
FileNotFoundErrorif no configuration file was found matching the criteria above.Returns
(None, None)if files were found but none could be parsed.
- load_ini_config(content)[source]¶
Utility method to parse INI configuration file.
Internal convention is to use a dot (
., as set byPARAM_PATH_SEP) in section IDs as a separator between levels. This is a workaround the limitation ofINIformat which doesn’t allow for sub-sections.Each value is converted to the type of the parameter its section and key address, like
[my-cli.subcommand]for the options ofsubcommand.Returns a ready-to-use data structure.
- load_argfile_config(content)[source]¶
Utility method to parse a plain-text argfile configuration file.
The file holds command-line tokens, one option per line, in the style of
mpv’s andyt-dlp’s configuration files:# Comments start with a hash sign. --option-name some value --flag
Tokens are split with
shlex.split(), so shell quoting rules apply and a#starts a comment. Each option is matched against the CLI’s root-level parameter declarations, and its value is converted to the parameter’s Python type, likeload_ini_config()does. A boolean flag needs no value: its primary declaration sets it toTrue, its secondary one (--no-*) toFalse. An option flaggedmultipleaccumulates one list item per occurrence. Unknown options are kept under a normalized key so the strict check can reject them like any other unrecognized configuration key, while positional tokens are skipped; subcommand options cannot be addressed from an argfile.Returns a ready-to-use data structure, wrapped in the app’s section name like the
[my-cli]section of the other formats.- Raises:
ValueError – the content cannot be tokenized, or an option is missing its value.
- Return type:
- load_sqlite_config(path)[source]¶
Utility method to parse a SQLite configuration database.
The database holds a single
SQLITE_CONFIG_TABLEtable ofkey/valuerows. Keys are parameter paths, with a dot (., as set byPARAM_PATH_SEP) separating each level, likemy-cli.default.int_param. Values are JSON-encoded, which carries every type the other formats do: booleans, numbers, strings, lists and nested objects alike.Returns a ready-to-use data structure.
Note
sqlite3is imported here and not at the top of the module, like the optional parsers ofparse_content(). A distribution can ship a Python without the SQLite bindings, and an unconditional import would then break every CLI at import time.ConfigFormat.SQLITE.enabledreports whether they are there, and the format is disabled if they are not.
- load_plist_config(path)[source]¶
Utility method to parse a
plistconfiguration file.The file is read as raw bytes and handed to the standard library’s
plistlib, which transparently decodes both the XML and the binary variants of the format. The XML variant also parses from a text payload throughparse_content(), which is how aplistfetched overhttp://orhttps://is loaded.Returns a ready-to-use data structure.
- load_xml_config(content)[source]¶
Utility method to parse an
XMLconfiguration document.parse_xml()collects the elements repeating a tag into a list, so a lone element reads as its text. An element naming a parameter that takes several values reads as a one-item list instead: XML has no other way to spell a list of one. Element names match parameters throughcanonical_param_name(), so the kebab-case spelling counts too.Returns a ready-to-use data structure.
- 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
ConfigValidatorinstances are stripped from the conf before dotted-key expansion and the CLI-parameter strict check, so user-controlled keys (like mappings whose keys are data, not flag names) neither split on a dot nor tripstrict=True.Note
load_conf()installs the same merged configuration, as part of the validation it runs: it does not call this method.- Raises:
ValidationError – in strict mode, on an invalid dotted key or a key matching no parameter.
- Return type:
- 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.
Relying on Click’s
default_mapkeeps the precedence: 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]andctx.meta[click_extra.context.CONF_FULL]respectively. This is the recommended way to identify which configuration file was loaded.There is no
ParameterSource.CONFIG_FILEenum member:ParameterSourceis a closed enum in Click, and monkeypatching it would be fragile. Config values end up indefault_map, so Click reports them asParameterSource.DEFAULT_MAP, which is accurate.- Return type:
- handle_parse_result(ctx, opts, args)[source]¶
Apply the reserved subcommand keys, once the configuration is loaded.
load_conf()runs as this option’s callback, from inside thesuper()call below, so the parsed document is already inctx.metawheninject_reserved_subcommands()reads it.Returning a rewritten
argsis what makes_default_subcommandsand_prepend_subcommandswork on any group class: Click threads the residual arguments through each parameter in turn, then hands the final list toGroup.parse_args, which splits it into the subcommands to dispatch. The group can be of a class click-extra does not own, so the option carries the feature instead of the group.Two cases never come here. On a bare invocation, Click raises the
no_args_is_helpscreen before it runs any parameter. A subgroup reached through this option holds no option of its own. Theclick.Group.parse_argsthis class installs covers both.Before loading, it reads the verbosity the command line asks for (see
requested_level()), soload_conf()can keep its status lines quiet under-qor a--verbosityaboveWARNING.
- class click_extra.config.option.NoConfigOption(param_decls=None, *, 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:
ExtraOptionA pre-configured option adding
--no-config.This option is supposed to be used alongside the
--configoption (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_CONFIGis theSentinelenum member that signals “skip configuration loading” toConfigOption. Click pickstype=UNPROCESSEDfor aflag_valueof a non-basic type, so the sentinel passes throughOptionunchanged.See also
An alternative implementation of this class would be to create a custom click.ParamType instead of a custom
Optionsubclass. Here is for example.
- class click_extra.config.option.ValidateConfigOption(param_decls=None, *, type=UNPROCESSED, metavar='LOCATION', is_eager=True, expose_value=False, help='Validate the configuration file and exit.', **kwargs)[source]¶
Bases:
ExtraOptionA pre-configured option adding
--validate-config LOCATION.Loads the config file at the given location, validates it against the CLI’s parameter structure in strict mode, reports results, and exits.
Note
The value is left
UNPROCESSEDso it accepts everythingConfigOptionaccepts: a file, a folder, a glob pattern, or anhttp://orhttps://URL. Both options read their value the same way, so a configuration a CLI can load is a configuration it can also validate.- 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
ValidationErrorshape so the reported path is always rooted at the configuration file:CLI-parameter strict check on the non-opaque part of the document.
Schema processing, if a
config_schemais configured: catches type errors and unknown keys inside the dataclass-described section.Each registered
ConfigValidatorruns against its declared opaque sub-tree.
Every detected error is emitted before exiting, so a single
--validate-configrun surfaces the full list of fixes the user needs to apply.- Return type: