"Is None" vs. "== None": A Beginner's Guide to Python Identity and Equality
Identity (is):
foo is None
checks if the objectfoo
is the exact same object as the special valueNone
.- Think of it like asking "are these two pointers pointing to the same memory location?"
- This is useful when you're working with specific objects and want to compare their identity, not just their value.
Equality (==):
foo == None
checks if the value offoo
is equal to the value ofNone
.- It's like asking "do these two values represent the same thing?"
- This is more commonly used for general value comparisons, regardless of the object itself.
Singularity of None:
- There's only one
None
object in Python. So, comparingNone
with itself usingis
will always be True. - But, comparing other objects with
None
usingis
might not be what you expect.
Custom comparison:
- While
None
has a default__eq__
method, other objects can define their own comparison logic. - This means
foo == None
might not always return True even iffoo is None
.
Simple case:
x = None
y = None
print(x is None) # True
print(x == None) # True (both check for None value)
z = 0
print(z is None) # False (different objects)
print(z == None) # False (different values)
Custom comparison:
class CustomObject:
def __eq__(self, other):
return other is None # Always equal to None
obj = CustomObject()
print(obj is None) # False (different objects)
print(obj == None) # True (custom logic)
Best Practice:- Use foo is None when you want to check if foo is the exact same object as None.
- Use foo == None when you want to check if the value of foo is equal to the value of None.
- Be aware that custom object comparisons might affect
==
behavior.
I hope this explanation clarifies the difference between is
and ==
with None
in Python!
python