Python’s equivalent of null (in Java/C#/JavaScript) or nil (in Ruby/Go/Swift) is the built-in singleton object None, which is the sole instance of the NoneType class and represents the intentional absence of a value. Because None is a single shared object in memory across the entire Python runtime, always test for it using identity operators (is None and is not None) rather than equality operators (== None).
Basic Example
# 1. Functions without an explicit return value implicitly return None
def log_message(msg: str) -> None:
print(f"[LOG] {msg}")
result = log_message("System initialized")
print(result) # Output: None
print(type(result)) # Output: <class 'NoneType'>
# 2. Always check for None using 'is' or 'is not' (PEP 8 standard)
user_email = None
if user_email is None:
print("No email address provided.")
if user_email is not None:
print(f"Sending to {user_email}")
Key Details & Mechanics
Noneis an immutable singleton (NoneType): Only oneNoneobject ever exists in memory during a Python process (id(None)is identical everywhere). You cannot instantiateNoneType()or subclass it, andNonecannot be reassigned (None = 1raises aSyntaxError).- Why
is Nonebeats== None:is Nonecompares object memory identity in a single pointer comparison ($O(1)$) and cannot be overridden.== Noneinvokes the left-hand object’s__eq__()dunder method, which can be customized by third-party classes (such as NumPy arrays, Pandas Series, or custom ORM models) to return a non-boolean object or raise aValueError.
- Falsy evaluation vs. explicit
is Nonechecks: In a boolean context (if x:),Noneevaluates toFalse—alongside0,0.0,"",[],{},set(), andFalse. Usingif not count:whencount = 0will mistakenly treat a valid zero the same as missing data (None). Always writeif count is None:when distinguishing “absent” from “empty or zero.” - Safe default mutable function arguments (
param=None): Never use a mutable object like[]or{}as a default parameter value (which is shared across all calls). Instead, default toNoneand initialize inside the function body:def append_item(item: str, target: list[str] | None = None) -> list[str]: if target is None: target = [] target.append(item) return target - Fallback defaults (
x if x is not None else default): Avoid writingval = user_input or "default"if0,"", orFalseare valid inputs, becauseortriggers on any falsy value. Useval = user_input if user_input is not None else "default"to fall back strictly when the value isNone.
Comparison of None Checks & Related Concepts
| Pattern / Construct | Evaluates True When |
Safe with Custom __eq__? |
Best Used When |
|---|---|---|---|
x is None |
x is strictly the None singleton |
Yes (pointer identity) | Checking if a variable, return value, or optional parameter is None. |
x is not None |
x is any object other than None |
Yes (pointer identity) | Guarding logic that requires a present value (even if 0 or ""). |
if not x: |
x is None, False, 0, "", [], {} |
Depends on __bool__ |
Checking if a collection or string is empty and None is treated identically. |
x == None |
x.__eq__(None) returns truthy |
No (can fail on NumPy/custom types) | Never—violates PEP 8 (E711) and risks subtle bugs. |
You must log in or register to comment.
