Yeda AI Tips · #105

Español

Never Cast an Env Var to Bool

This one-line config bug turns your kill switch on. Environment variables are always strings, and in almost every language a non-empty string is truthy — so bool(os.environ["KILL_SWITCH"]) returns True whether the operator set it to "true", "false", or "0". The flag you built to stop the system just became a flag that can't say no.

Why the raw cast lies

Python's truth-value rule is about emptiness, not meaning: an object is true unless it's one of the documented falsy values — None, False, numeric zero, or an empty collection like ''. The string "false" has five characters, so it's truthy. The same trap exists across the stack:

There are exactly two string values a raw cast handles correctly: unset and empty. Everything an operator would actually type — true, false, 1, 0, yes, no — is either mishandled or half-handled.

Parse through one shared vocabulary

The fix is a single parser with an explicit true/false vocabulary, used for both env vars and structured config, so false means false everywhere:

_TRUE  = {"1", "true", "t", "yes", "y", "on"}
_FALSE = {"0", "false", "f", "no", "n", "off"}

def env_bool(name: str, default: bool = False) -> bool:
    raw = os.environ.get(name)
    if raw is None or raw.strip() == "":
        return default          # blank template value != forced off
    v = raw.strip().lower()
    if v in _TRUE:
        return True
    if v in _FALSE:
        return False
    raise ValueError(f"{name}={raw!r} is not a boolean")

Three properties matter more than the exact word list:

PropertyWhy it matters
Unset/blank → defaultAn empty FLAG= line in a .env template shouldn't force the flag off (or on)
Unknown value → errorFLAG=fales should crash at startup, not silently pick a side
One vocabulary everywhereEnv vars, YAML, and CLI flags must agree on what "false" is

That last row is the subtle one. If your env parser accepts yes but your YAML loader doesn't, the same deployment value flips meaning depending on where it's written.

Prior art: what real parsers accept

The twelve-factor methodology pushes config into env vars precisely because they're a language- and OS-agnostic standard — which is also why they can only carry strings. The type discipline is your job.

Power-user notes

Resources

This article pairs with reel #105 of the Yeda AI Tips series. Building an AI-assisted engineering workflow? Yeda AI designs, audits, and ships production LLM systems.

Talk to us · Read the blog · Leer en español