None#
None is the single instance of NoneType. It stands in
for “no value”, “not applicable”, or “not yet computed”. Use
is None and is not None for null checks; comparison by
identity is the idiom.
x = None
if x is None:
x = compute_default()
def find(xs, predicate):
for x in xs:
if predicate(x):
return x
return None # explicit "no result"
== None works but reads as a junior tell. is compares
identity and is what the type system, linters, and PEP 8 expect.
Functions without an explicit return implicitly return
None. Use this for command-style functions; for query-style
functions, prefer an explicit return None to signal intent.
Methods#
None has no methods. The operations the operator runs
against it are identity tests with is and is not and the
truthiness rules; None is falsy.
Call |
Effect |
|---|---|
|
Identity test; idiomatic null check. |
|
Negated identity test. |
|
|
Idiomatic null check.
x = None
x is None
True
Truthiness: None is falsy.
bool(None)
False
None is hashable and can sit in a set or as a dict key.
hash(None) == hash(None)
True
Operator overloading#
None participates in identity comparisons and the truthiness
predicate; the arithmetic and sequence dunders are absent.
Operator |
Dunder |
Returns |
|---|---|---|
|
– |
Identity test (compares pointers; not overloadable). |
|
|
Equality; works but reads as a junior tell. |
|
|
Always |
|
|
Constant; |
__eq__ is the only dunder relevant to a custom class that
wants to compare equal to None; is None cannot be
overridden.
class Missing:
def __eq__(self, other): return other is None
def __hash__(self): return hash(None)
Missing() == None
True
A sentinel object is the operator’s “explicit absence” when
None is a valid value of the function’s domain. object()
makes a unique identity-comparable instance.
MISSING = object()
def get(d, key):
v = d.get(key, MISSING)
return "absent" if v is MISSING else v
get({"a": None}, "a"), get({"a": None}, "b")
(None, 'absent')