Use if x is None: and if x is not None: (identity comparison via the is operator) rather than == None or if not x:, because None is a single global singleton (NoneType) in Python, is compares memory identity in $O(1)$ without invoking custom __eq__ dunder methods, and if not x: mistakenly matches falsy values like 0, 0.0, "", [], {}, and False.

Basic Example

def greet(username: str | None) -> str:
    # 1. Recommended: Explicit identity check with `is None` / `is not None`
    if username is None:
        return "Hello, Guest!"
    return f"Hello, {username}!"

print(greet(None))   # Output: Hello, Guest!
print(greet(""))     # Output: Hello, !  (empty string is NOT treated as `None`)
print(greet("Zain")) # Output: Hello, Zain!

# 2. Negated check (PEP 8 prefers `x is not None` over `not x is None`):
result = 0
if result is not None:
    print(f"Valid numeric result: {result}")
# Output: Valid numeric result: 0

Key Details & Edge Cases

  • Why if not x: breaks on valid falsy values (0, "", [], False):
    • In Python, 0, 0.0, "", [], {}, set(), and False all evaluate to False in a boolean context (bool(x) == False). Checking if not count: when count = 0 treats a valid zero count identically to missing data (None). Use if count is None: whenever 0, "", or [] are legitimate values.
  • Why is None beats == None (custom __eq__ bugs & Pandas/NumPy ambiguity):
    • == calls x.__eq__(None), which a custom class can override to return True or raise an exception, and on a NumPy array or Pandas Series arr == None performs element-wise comparison returning a boolean array (ValueError: The truth value of an array with more than one element is ambiguous), whereas arr is None reliably tests whether the variable itself is None.
  • PEP 8 style rule (x is not None vs. not x is None):
    • Although Python compiles not x is None and x is not None to the exact same bytecode, PEP 8 (enforced by flake8 E714 and ruff E714) strictly mandates if x is not None: for readability.
  • Assigning default fallbacks cleanly (x if x is not None else default):
    • Avoid port = config_port or 8080 when 0 could be passed intentionally; instead write port = config_port if config_port is not None else 8080.
  • Checking for missing values (NaN / pd.NA / None) in Pandas & NumPy:
    • None is None is True, but float("nan") is None and np.nan is None are False. Inside Pandas or NumPy datasets, check pd.isna(val) (which returns True for None, np.nan, pd.NA, and pd.NaT) rather than val is None.

Comparison of None and Emptiness Checking Idioms in Python

Expression True for None? True for 0, "", [], False? Invokes Custom __eq__? Best Used When
x is None / x is not None (Recommended) Yes / No No / Yes No ($O(1)$ pointer identity) Checking whether an optional variable, default argument, or return value is specifically None.
if not x: / if x: Yes / No Yes / No No (calls __bool__ / __len__) Checking whether a container (list, str, dict) is empty when None is not a distinct case.
x == None / x != None Yes / No No / Yes Yes (can break on custom classes/arrays) Never recommended—violates PEP 8 (E711) and fails on NumPy/Pandas objects.
pd.isna(x) (Pandas) Yes No N/A Checking scalar cells or Series/DataFrames where None, np.nan, and pd.NA all represent missing data.