Sub topic 7
Identity versus equality: is and ==
This chapter assumes you can run Python code and know the built-in types int, str, list and dict. It also assumes you know that a variable name refers to an object. It explains what == and is test, why they can disagree, and which one to use in each case.
Two different questions
Python gives you two operators for asking whether two things are "the same", and they ask different questions.
a == basks whether the two objects have equal values. Python callsa.__eq__(b), and the class decides what "equal" means.a is basks whether both names refer to the very same object in memory. Python does not call any method. It compares the identities of the two objects.
Every object has an identity that never changes during its life. In CPython, the standard implementation, id(obj) returns it. a is b is equivalent to id(a) == id(b).
a = [1, 2]
b = [1, 2]
c = a
print(a == b)
print(a is b)
print(c is a)
value = None
print(value is None)The output is True, False, True, True. The two lists hold equal values but were built separately, so they are two objects. The name c was bound to the object that a already referred to, so no new object exists.
Why identity matters: aliasing
Identity explains a common surprise with mutable objects. Assignment never copies. It binds another name to the same object.
a = [1, 2]
c = a
c.append(3)
print(a)
print(a is c)
b = a.copy()
print(b == a)
print(b is a)The output is [1, 2, 3], True, True, False. Changing the list through c changes it for a, because both names refer to one object. a.copy() makes a new object with equal contents. That is why b == a is true while b is a is false.
Use is for None and other singletons
Some objects are singletons: the language guarantees only one exists. None, True, False and Ellipsis are singletons. For these, is is the correct and idiomatic test.
value = None
if value is None:
print("nothing here")Prefer is None over == None for two reasons. First, == can be overridden, so a class may claim to equal None. Second, is cannot be overridden and is slightly faster.
class Always:
def __eq__(self, other):
return True
x = Always()
print(x == None)
print(x is None)The output is True then False. Only is gives the answer you want.
A related point concerns booleans. 1 == True is True, because bool is a subclass of int, but 1 is True is False. To check whether a value is the boolean True itself, use is True. To check whether it is merely truthy, write if value:. Chapter on truthiness covers that distinction.
Do not use is to compare numbers or strings
Beginners sometimes find that is "works" on small numbers or short strings and conclude it is a faster ==. This is an accident of implementation.
CPython keeps a cache of small integers, currently -5 to 256, and may reuse equal string constants. The compiler may also merge equal constants within one block of code. None of this is part of the language definition. It differs between Python versions and between implementations such as PyPy. It can even differ between two lines in the same file.
So the result of x is y for equal numbers or strings is unpredictable. The only reliable statement is that it is not guaranteed to be True. Since Python 3.8, the compiler emits a SyntaxWarning when you write is against a literal such as x is 1000 or name is "admin". Treat that warning as a bug report on your code.
Equality is not always reflexive
You might expect x == x to always be true. For floating-point NaN (not a number), it is not. By the IEEE 754 standard, NaN is not equal to anything, including itself.
nan = float("nan")
print(nan == nan)
print(nan is nan)
print(nan in [nan])
print(float("nan") in [nan])The output is False, True, True, False. The third line is the surprising one. Containers such as lists check identity first and fall back to == only if identity fails. So nan in [nan] succeeds because the same object is found, even though nan == nan is false. A freshly created NaN is a different object and is not found. To detect NaN reliably, use math.isnan(x).
Custom equality
When you write a class, == defaults to identity. The inherited object.__eq__ returns true only for the same object. To compare by value, define __eq__.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
if not isinstance(other, Point):
return NotImplemented
return (self.x, self.y) == (other.x, other.y)
def __hash__(self):
return hash((self.x, self.y))
p = Point(1, 2)
q = Point(1, 2)
print(p == q)
print(p is q)
print(p == (1, 2))The output is True, False, False. Returning NotImplemented for foreign types lets Python try the other operand's __eq__. If both decline, == falls back to an identity check, which is false here.
Two further rules apply. A class that defines __eq__ without __hash__ becomes unhashable, so it cannot be a dictionary key or set member. Objects that compare equal must also have equal hashes, which is why the class above defines __hash__ from the same fields. Only define __hash__ this way if the fields do not change after creation.
A legitimate use of is: sentinels
Sometimes None is itself a valid argument, and you need a way to tell "not provided". Create a unique object and compare by identity.
_MISSING = object()
def lookup(mapping, key, default=_MISSING):
if key in mapping:
return mapping[key]
if default is _MISSING:
raise KeyError(key)
return default
settings = {"debug": False}
print(lookup(settings, "debug"))
print(lookup(settings, "mode", None))The output is False then None. Because _MISSING is a private object that no caller can accidentally pass, is is exact here. == would work only if the caller's objects never claimed equality with it.
Choosing the right test
| You want to know | Use | Notes |
|---|---|---|
| Do two values hold the same data? | `==` | Uses `__eq__`, so it works for numbers, strings, lists and your own classes. |
| Is this the `None` singleton? | `is None` | Cannot be fooled by a custom `__eq__`. |
| Are two names bound to one object? | `is` | Useful for detecting aliasing and for sentinels. |
| Is the item in a collection? | `in` | Checks identity first, then `==`. |
| Are two floats close? | `math.isclose` | Float rounding makes `==` unreliable. |
Common errors
- Writing
if x is "yes":. This may work in tests and fail later. Use==. - Writing
if x == None:. It works for ordinary values, butis Noneis the standard form and is safe against custom__eq__. - Assuming
b = acopies a list or dictionary. Usea.copy(),list(a)orcopy.deepcopy(a)when you need a separate object. - Defining
__eq__and forgetting__hash__, then gettingTypeError: unhashable type. - Using
is notincorrectly. Writex is not None, notnot x is None. Both work, but the first is the idiom and reads as one operator.
Exercise
Predict the output of the following code, then explain the last line in terms of identity and equality. a = [1, 2] b = a c = [1, 2] b.append(3) print(a == c, a is b, a is c) print(c in [a, b, c])
Show answer
The first line prints False True False. Appending through b changes the object shared with a, so a is now [1, 2, 3]. It is no longer equal to c, which is [1, 2]. a is b is true because they share one object. a is c is false because c is a separate object. The second line prints True. in checks each element by identity first and then by ==. The first two elements are not equal to c, and the third element is c itself, so the identity check succeeds.
Exercise
Why is if user is None: preferred over if user == None:, and why is if status is "ok": a bug?
Show answer
None is a singleton, so is identifies it exactly. == can be changed by a class's __eq__, so an object could report that it equals None. A string such as "ok" is a value type. Whether two equal strings are the same object depends on interning and compiler optimizations, which are implementation details. status is "ok" can therefore be false even when the text matches. Use status == "ok".