Python › Command-Line Interfaces (argparse)

How would you build a CLI tool where some arguments can also be set via environment variables, falling back to a default if neither is provided?

Advanced

Answer

Read the relevant environment variable with os.environ.get() as the DEFAULT value passed to add_argument(), so an explicit command-line flag always overrides the environment variable, which in turn overrides a final hardcoded fallback default.
import os

parser.add_argument(
    "--api-key",
    default=os.environ.get("MY_APP_API_KEY"),
    required=os.environ.get("MY_APP_API_KEY") is None,
    help="API key (or set MY_APP_API_KEY environment variable)"
)
Real-world example Allowing a CLI tool's API key or config path to be set via an environment variable in CI, while still supporting an explicit --api-key override locally.

Common follow-ups: What precedence order makes the most sense: CLI flag, environment variable, or config file default?