Python None comparison: should I use is or ==?
Python None comparison: should I use is or ==?
Summary:
Use is
when you want to check against an objects identity (e.g. checking to see if var
is None
). Use ==
when you want to check equality (e.g. Is var
equal to 3
?).
Explanation:
You can have custom classes where my_var == None
will return True
e.g:
class Negator(object):
def __eq__(self,other):
return not other
thing = Negator()
print thing == None #True
print thing is None #False
is
checks for object identity. There is only 1 object None
, so when you do my_var is None
, youre checking whether they actually are the same object (not just equivalent objects)
In other words, ==
is a check for equivalence (which is defined from object to object) whereas is
checks for object identity:
lst = [1,2,3]
lst == lst[:] # This is True since the lists are equivalent
lst is lst[:] # This is False since theyre actually different objects
is
is generally preferred when comparing arbitrary objects to singletons like None
because it is faster and more predictable. is
always compares by object identity, whereas what ==
will do depends on the exact type of the operands and even on their ordering.
This recommendation is supported by PEP 8, which explicitly states that comparisons to singletons like None should always be done with is
or is not
, never the equality operators.
Python None comparison: should I use is or ==?
PEP 8 defines that it is better to use the is
operator when comparing singletons.