Skip to content

Lesson 4 of 9 · 22m

Configuration Files Without Precedence Surprises

Layer defaults, config files, environment variables, and flags in a predictable order, and put files where operators expect them.

Every configuration system eventually answers the same question: which value wins? If the answer depends on which module read the file first, your users will eventually ship production secrets into dotfiles or wonder why cron behaves differently than their shell. Decide precedence once and implement it in one place.

The precedence ladder should be boring

built-in defaults
  < system config file
    < user config file
      < environment variables
        < command-line flags

CLI flags win because they are the most specific expression of intent for this invocation. Environment variables are next because deployment systems use them per process. Files are durable defaults. Document the order in --help or the man page; do not make users reverse-engineer it.

TOML is a good default for application config

# ~/.config/fleetctl/config.toml
endpoint = "https://fleet.internal.example"
timeout_seconds = 10
output = "json"

[auth]
token_file = "~/.config/fleetctl/token"

Python 3.11+ includes tomllib for reading TOML. It is stricter and safer than inventing an INI dialect, and unlike YAML it does not surprise you with type coercion such as yes becoming a boolean in some parsers.

Put files in XDG locations on Linux

from pathlib import Path
import os

def user_config_path(app_name: str) -> Path:
    root = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config"))
    return root / app_name / "config.toml"

Merge explicitly, not recursively by accident

config = dict(DEFAULTS)
config.update(read_file_values(path))
config.update(read_env_values(prefix="FLEETCTL_"))
if cli_timeout is not None:
    config["timeout_seconds"] = cli_timeout

Deep-merge only when nested sections genuinely need it. Recursive merging looks clever until a user tries to replace a list and your code unions it with the default. Scalars replace, lists usually replace, and unknown keys should warn or fail depending on how dangerous silence would be.

Secrets do not belong in world-readable config

Reference secret files or environment variables instead of embedding credentials. If the file must contain a token, check permissions and refuse to run when it is group/world-readable on Unix. Silent insecurity is worse than an inconvenient error.

Field notes

  • Validate configuration before doing work. timeout_seconds = "ten" should fail during startup, not after the first network mutation.
  • Show effective configuration with a config inspect or --show-config command, redacting secrets.
  • Environment variable names should be prefixed: FLEETCTL_ENDPOINT, not ENDPOINT.
  • Windows, macOS, and Linux have different config conventions; platformdirs is worth its small dependency for cross-platform tools.

Was this lesson helpful?

Sign in to rate