Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python Click Environment Variables: Options and Defaults

Learn how to configure Click CLI options from environment variables, including defaults, automatic prefix mapping, precedence, and testing.

~4 min readPython
#Click#Environment Variables#CLI#Python
Diagram showing a Python Click CLI option reading its value from an environment variable.

Click lets you configure command-line options from environment variables with the envvar parameter, and it can map options automatically with auto_envvar_prefix. The precedence is straightforward: command-line values override environment variables, and environment variables override defaults. This article explains how to use these features and where they commonly break.

Why Environment Variables Matter in Click

A Click command often needs values that vary by deployment: API keys, database URLs, feature flags. Hardcoding them into the script is fragile, and passing every value as a command-line argument becomes tedious. Environment variables solve this by letting the surrounding shell or orchestration system provide values. Click integrates with this pattern directly through the envvar option parameter, which makes an option read from a specified environment variable when no command-line value is given.

Declaring an Option That Reads from an Environment Variable

The simplest usage is to pass envvar to click.option. When the environment variable is set, Click uses its value for the option. The user can still override it with the command-line flag.

python
import click @click.command() @click.option('--api-key', envvar='MYAPP_API_KEY') def cli(api_key): click.echo(f'Using API key: {api_key}')

If MYAPP_API_KEY is set, running the command without --api-key picks it up. If the user passes --api-key, that value wins. If neither is provided, the option is None unless a default is set.

Using Environment Variables as Defaults

You can combine envvar with default to provide a fallback. The environment variable, when present, overrides the default. This is useful for optional configuration with a sensible fallback.

python
@click.option('--port', default=8080, envvar='MYAPP_PORT', type=int)

Here MYAPP_PORT is read as a string and converted to an integer because of type=int. If the variable is unset, the default 8080 is used. This pattern is common for ports, timeouts, and other numeric settings.

Automatic Mapping with auto_envvar_prefix

Specifying envvar for every option can become repetitive. Click provides auto_envvar_prefix as a context setting that automatically maps options to environment variables. The variable name is the prefix, an underscore, and the option name in uppercase. Hyphens in option names become underscores.

python
@click.command(context_settings={'auto_envvar_prefix': 'MYAPP'}) @click.option('--host') @click.option('--port', type=int) def cli(host, port): click.echo(f'{host}:{port}') if __name__ == '__main__': cli()

With this setup, MYAPP_HOST and MYAPP_PORT are used automatically. For a command group, set the prefix in the top-level command's context settings so options on subcommands inherit it. This is a convenient way to standardize configuration naming across a CLI.

Precedence: Command Line, Environment, Default

Click's precedence is explicit: command-line arguments override environment variables, which override defaults. This is the behavior you get with envvar and auto_envvar_prefix. If you need to compute a fallback from an environment variable yourself, you can read it when defining the option, but be aware that the default is evaluated once when the module is imported.

python
import os @click.command() @click.option('--debug', default=os.environ.get('MYAPP_DEBUG', False), is_flag=True) def cli(debug): click.echo(f'Debug: {debug}')

This approach is less flexible than envvar because it does not re-read the environment variable each time the command runs. In practice, stick with Click's built-in precedence unless you have a specific reason to compute defaults outside Click.

Type Conversion and Boolean Handling

Environment variables are always strings. Click applies type conversion based on the type parameter. For integers, floats, and paths, this works transparently. Booleans also use a built-in converter that recognizes common string forms: 1, true, t, yes, y, and on become True; 0, false, f, no, n, and off become False.

python
@click.option('--debug', envvar='MYAPP_DEBUG', type=bool)

If you need stricter or non-standard boolean strings, define a custom callback or use click.Choice so the accepted values are explicit. The built-in bool type is the simplest choice when users can use conventional yes/no values.

Common Pitfalls: Empty Strings and Missing Variables

An environment variable set to an empty string is not the same as unset. Click treats an empty string as a provided value, which can cause validation errors or unexpected type conversion failures. For example, MYAPP_PORT= with type=int raises a BadParameter error because an empty string cannot be converted to an integer.

To treat an empty string as missing, you can use a custom callback that checks for emptiness and substitutes a default. Alternatively, ensure the environment does not export empty variables. When a variable is entirely absent, and the option is not marked required, Click falls back to the default or leaves the option as None if no default is given.

Testing and Production Considerations

When testing a Click command, you can set environment variables using monkeypatch or os.environ. The CliRunner from Click's testing module supports an env parameter that sets environment variables for the isolated invocation.

python
from click.testing import CliRunner def test_cli_envvar(): runner = CliRunner() result = runner.invoke(cli, [], env={'MYAPP_HOST': 'example.com'}) assert result.exit_code == 0

In production, environment variables are a common way to inject configuration, but they are visible in the process environment and can leak through debugging tools or crash reports. Avoid putting highly sensitive data in environment variables if a config file with restricted permissions is an option. Also, be aware that auto_envvar_prefix can expose internal option names as environment variables; document the expected variables clearly.

For maintainability, centralize environment variable names in a constants module or use a configuration loader that maps them to Click options. This reduces duplication and makes the CLI's configuration surface explicit. When a variable is required for the command to work, set required=True on the option so Click enforces its presence, whether from the environment or the command line.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.