r/CloudandCode • Founder | YourCloudDude • 24d ago

Guide [Python] DEBUG="false" can still turn a flag on: parse configuration explicitly

A small deployment bug to watch for:

bool("false")  # True
bool("0")      # True

These are non-empty strings. Python is testing whether the string is empty, rather than interpreting a configuration value.

Environment variables arrive as strings, so bool(os.getenv("DEBUG")) is an unsafe way to parse a true/false flag.

A small parser you can reuse

Save this as config_demo.py. It uses only the standard library:

import os

def read_bool(name, default=False):
    raw = os.getenv(name)
    if raw is None:
        return default
    values = {
        "true": True, "1": True, "yes": True,
        "false": False, "0": False, "no": False,
    }
    key = raw.strip().lower()
    if key not in values:
        raise ValueError(f"{name} must be true/false, 1/0 or yes/no")
    return values[key]

print("DEBUG:", read_bool("DEBUG"))

Run it with python config_demo.py. With DEBUG unset, the output is DEBUG: False.

Test these cases

| DEBUG value | Result | |---|---| | unset | False | | false, 0, no | False | | true, 1, yes | True | | TRUE | True | | empty string or maybe | ValueError |

Rejecting an invalid value helps expose a deployment typo instead of silently choosing a surprising behavior. The error names the setting without printing its raw value.

Extend it

Add a separate PORT parser that accepts only integers from 1 to 65535. Decide explicitly whether a missing setting uses a default and whether an empty setting is an error.

Keep configuration parsing near startup so a bad setting fails before the application starts accepting work. Only log settings you have deliberately classified as safe to disclose.

References: Python truth value testing, environment variables.

1 Upvotes

0 comments sorted by