Sub topic 8
is versus ==
This chapter assumes you know Python variables, if statements, and the built-in types list, int, and str. It also assumes you know that None is Python's "no value" object.
Two questions, two operators
Python has two operators that both look like "are these the same?" They answer different questions.
==asks whether two objects have equal values. The objects decide this by running their__eq__method.isasks whether two names refer to the very same object in memory. Python cannot override this check.
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a == b) # True: same contents
print(a is b) # False: two separate list objects
print(a is c) # True: c is another name for a's object
print(id(a) == id(c)) # True: same identityEvery object has an identity, which id() returns. In CPython, the standard implementation, this is the object's memory address. The expression x is y compares id(x) with id(y).
What each operator costs and trusts
is is a single pointer comparison. It never calls your code, so it cannot be fooled. == runs __eq__, which can be slow, can return surprising answers, and can be defined by any class.
| Operator | Compares | Can a class change it? | Typical use |
|---|---|---|---|
| `==` | Values | Yes, through `__eq__` | Numbers, strings, lists, your own value types |
| `is` | Identity | No | `None`, sentinel objects, "same object?" checks |
Why None uses is
None is a singleton. Only one None object exists in a running program, so identity is a precise test for it. Using is also protects you from classes that define __eq__ loosely:
class AlwaysEqual:
def __eq__(self, other):
return True
obj = AlwaysEqual()
print(obj == None) # True: the class claims equality with everything
print(obj is None) # False: identity cannot be overriddenLibraries such as NumPy also override == so that comparing to None does not return a plain bool. The rule is to write x is None and x is not None. Do not write not x is None. It works, but is not is a single operator and reads better.
Do not use is for numbers and strings
CPython caches some small integers and some strings as an optimization. That makes is appear to work on them, until it does not:
a = int("1000")
b = int("1000")
print(a == b) # True
print(a is b) # False in CPython: two separate int objectsWhether two equal numbers or strings share one object is an implementation detail. It can differ between Python versions, between interpreters, and between code written as literals and code computed at run time. Python 3.8 and later also emits a SyntaxWarning for code like x is 1000. Use == for values.
Where is is the right tool
Use is for these cases:
- Testing for
None:if result is None:. - Testing for
TrueorFalseexactly, which is rare. Prefer plain truthiness, as inif flag:, in most code. - Sentinel objects. A sentinel is a unique object that you create to mean "not provided", for cases where
Noneis itself a valid input:
_MISSING = object()
def get_value(data, key, default=_MISSING):
if key in data:
return data[key]
if default is _MISSING:
raise KeyError(key)
return default
settings = {"timeout": None}
print(get_value(settings, "timeout")) # None
print(get_value(settings, "retries", 3)) # 3
print(get_value(settings, "retries", None)) # NoneHere None is a legitimate default that callers may pass. Only a fresh object() that nobody else holds cannot be confused with real input.
Common errors
- Writing
if x == None:. It usually works, but it calls__eq__and can be wrong for objects that override it. - Using
isto compare strings or numbers because it "worked in the shell". - Using
==to ask "are these the same list?" when you need to know whether mutating one will change the other. Useisfor that question.
Exercise
Given x = [1, 2], y = [1, 2], and z = x, what do x == y, x is y, and z is x print? After z.append(3), what does x contain, and what does y contain?
Show answer
x == y prints True, x is y prints False, and z is x prints True. z and x name the same list, so after z.append(3), x is [1, 2, 3]. y is a separate list and stays [1, 2].
Exercise
Why is if value is None: safer than if value == None: when value may be an instance of a class that defines __eq__?
Show answer
is compares identity and cannot be overridden, so it is true only for the real None singleton. == calls the class's __eq__, which may return True for None (or a non-bool value) even though the object is not None.