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(), andFalseall evaluate toFalsein a boolean context (bool(x) == False). Checkingif not count:whencount = 0treats a valid zero count identically to missing data (None). Useif count is None:whenever0,"", or[]are legitimate values.
- In Python,
- Why
is Nonebeats== None(custom__eq__bugs & Pandas/NumPy ambiguity):==callsx.__eq__(None), which a custom class can override to returnTrueor raise an exception, and on a NumPy array or Pandas Seriesarr == Noneperforms element-wise comparison returning a boolean array (ValueError: The truth value of an array with more than one element is ambiguous), whereasarr is Nonereliably tests whether the variable itself isNone.
- PEP 8 style rule (
x is not Nonevs.not x is None):- Although Python compiles
not x is Noneandx is not Noneto the exact same bytecode, PEP 8 (enforced byflake8E714 andruffE714) strictly mandatesif x is not None:for readability.
- Although Python compiles
- Assigning default fallbacks cleanly (
x if x is not None else default):- Avoid
port = config_port or 8080when0could be passed intentionally; instead writeport = config_port if config_port is not None else 8080.
- Avoid
- Checking for missing values (
NaN/pd.NA/None) in Pandas & NumPy:None is NoneisTrue, butfloat("nan") is Noneandnp.nan is NoneareFalse. Inside Pandas or NumPy datasets, checkpd.isna(val)(which returnsTrueforNone,np.nan,pd.NA, andpd.NaT) rather thanval 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. |
You must log in or register to comment.
