PYTHON Contents

Conditionals and Truthiness

Write conditionals that are explicit about None and falsy values, using guard clauses to keep logic predictable.

On this page

Truthiness

Empty containers, 0, and None are falsy. This can be useful, but it can also hide bugs.

Guard Clauses

def process(user: dict) -> str:
    if not user:
        raise ValueError("user required")

    user_id = user.get("id")
    if user_id is None:
        raise ValueError("user.id required")

    return f"ok:{user_id}"

Beware of or-default

timeout = config.get("timeout") or 10  # BUG if timeout can be 0

If 0 is a valid value, use an explicit is None check instead.

Operational Checklist

  • Decide whether 0/""/empty containers are valid values.
  • Use explicit is None checks where it matters.
  • Avoid deeply nested conditionals; split logic into small functions.

Failure Modes

  • Falsy bug: valid values drop into defaults unexpectedly.
  • Complex logic: multi-and/or conditions become untestable.