Python's bool data type has two constant values: True and False. The bool class is a subclass of int (True == 1 and False == 0).
flowchart TD
A["Expression Evaluation"] --> B{"Is value zero, None, or empty?"}
B -- "Yes (0, None, '', [], {}, set())" --> C["Falsy (Evaluates to False)"]
B -- "No (Any non-zero/non-empty)" --> D["Truthy (Evaluates to True)"]
The following objects evaluate to False in conditional contexts:
None, False0, 0.0, 0j, Decimal(0)"", (), [], {}, set(), range(0)from typing import List, Optional
def authenticate_session(user_token: Optional[str], roles: List[str]) -> bool:
"""Demonstrate short-circuit evaluation and boolean rules."""
# Short-circuiting 'and': If user_token is Falsy, roles check is skipped entirely
is_valid_user = bool(user_token) and ("admin" in roles or "editor" in roles)
return is_valid_user
def demonstrate_boolean_subclassing() -> None:
# Booleans are integers under the hood
print(f"True + True = {True + True}") # Output: 2
print(f"False * 100 = {False * 100}") # Output: 0
print(f"isinstance(True, int): {isinstance(True, int)}") # Output: True
if __name__ == "__main__":
print("Session 1 Auth:", authenticate_session("token_abc123", ["editor", "user"]))
print("Session 2 Auth:", authenticate_session("", ["admin"]))
demonstrate_boolean_subclassing()
if items: instead of if len(items) > 0: to check if a collection is non-empty.and and or return the actual evaluating operand rather than strictly converting to a boolean.is for Singletons: Always compare against None using if var is None: or if var is not None: instead of ==.Write a function validate_config(config: dict) -> bool that checks if the dictionary is non-empty, contains the key "active", and that config["active"] is Truthy.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With