Environment variables¶
Click’s environment-variable handling spreads across several internal methods on Parameter, Option, and Context. This module centralizes that logic into a small set of pure helpers that downstream code can call to introspect what Click would read for a given parameter, plus a couple of subprocess-friendly conveniences.
The helpers underpin click-extra’s show_envvar defaults on every option’s help screen, the --show-params table, and the auto-envvar reconciliation in TelemetryOption, ColorOption, and others — but they’re equally useful for any downstream code that needs to surface the env-var contract of its CLI.
See also
Environment variables are a legacy mess: Let’s dive deep into them is the best survey of the wider problem space these helpers paper over.
merge_envvar_ids(*envvar_ids)¶
Merge and deduplicate environment-variable names from any combination of strings and arbitrarily-nested iterables. None values are filtered out. Order is preserved (first occurrence wins), and on Windows every name is upper-cased to match the platform’s case-insensitive os.environ semantics — the same normalization the standard library applies internally.
('MYAPP_DEBUG',)
('MYAPP_DEBUG', 'MYAPP_VERBOSE')
('A', 'B', 'C')
The result is a tuple[str, ...] ready to feed Click’s envvar= parameter on options and arguments. Click Extra uses it internally to combine user-supplied envvar names with conventions like NO_COLOR, DO_NOT_TRACK, and FORCE_COLOR:
# click_extra/telemetry.py
envvar = merge_envvar_ids("DO_NOT_TRACK", envvar)
clean_envvar_id(name)¶
Normalize an arbitrary string into a canonical environment-variable name: split on non-alphanumeric runs, drop empties, join with underscores, uppercase the result.
MY_CLI
MY_CLI_DEBUG_MODE
V2_0_BETA
Attention
This helper does not exactly replicate Click’s own auto-envvar derivation: Click’s case-handling of environment variables is inconsistent across versions. Use clean_envvar_id when you control the naming, and param_auto_envvar_id (below) when you need to know exactly what Click itself would produce for a given parameter.
param_auto_envvar_id(param, ctx)¶
Compute the auto-generated environment variable Click would read for an option or argument, given a parameter instance and either an active click.Context or a plain settings dict (e.g. context_settings). Returns None when the parameter has allow_from_autoenv=False, or when no auto_envvar_prefix is configured. The output exactly mirrors what click.core.Parameter.resolve_envvar_value() and click.core.Option.resolve_envvar_value() produce internally:
MYAPP_DEBUG
None
param_envvar_ids(param, ctx) — the main entry point¶
Returns the deduplicated, ordered tuple of environment variables Click would consider for an option or argument: the user-declared envvar= value (single string or iterable) followed by the auto-generated one. Click reads them in this order and stops at the first one set, which means user-declared envvars take precedence over the auto-generated one — param_envvar_ids preserves that ordering.
--debug: ('DEBUG', 'MYAPP_DEBUG')
--verbose: ('MYAPP_VERBOSE',)
This is what powers click-extra’s --show-params table: each row’s Env. vars. column comes from param_envvar_ids(param, ctx), joined with , and styled with the active theme’s envvar slot.
env_copy(extend=None)¶
Returns a shallow copy of os.environ with optional extra keys layered on top, or None when extend is empty. Mirrors Python’s own subprocess-handling pattern — subprocess.Popen(env=None) inherits the current environment, so returning None for the no-extension case is a useful contract:
None
None
False
1
False
Pair it with subprocess.run(..., env=env_copy({"MYAPP_TOKEN": secret})) when you need to add a few variables for a child process without leaking them into the parent’s os.environ.
click_extra.envvar API¶
Implements environment variable utilities.
- 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.
Nonevalues are ignored.Variable names are deduplicated while preserving their initial order.
Caution
On Windows, environment variable names are case-insensitive, so we normalize them to uppercase as the standard library does.
Returns a tuple of strings. The result is ready to be used as the
envvarparameter for Click’s options or arguments.
- 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 is not consistent regarding case-handling of environment variable.
- Return type:
- 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 as it is exactly computed within Click’s internals, i.e.
click.core.Parameter.resolve_envvar_value()andclick.core.Option.resolve_envvar_value().
- 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().
- click_extra.envvar.env_copy(extend=None)[source]¶
Returns a copy of the current environment variables and eventually
extendit.Mimics Python’s original implementation by returning
Noneif noextendcontent are provided.Environment variables are expected to be a
dictofstr:str.