Sub topic 8
is versus ==
This chapter assumes you know Python comparison operators, how None works, and how to define a simple class. You should also know that variables hold references to objects, not copies of them. By the end you will be able to say which question each operator asks, predict results when objects are shared or copied, and choose the right operator for None, sentinels, and booleans.
Two different questions
Python has two operators that look like they test "sameness," but they ask different questions.
a == basks: do these two objects have equal values?a is basks: are these two names bound to the very same object?
== is decided by the objects' types. is is decided by object identity, which Python does not let you override.
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
c.append(4)
print(a) # [1, 2, 3, 4]
print(b) # [1, 2, 3]c = a copies the reference, not the list. Changing the list through c is visible through a, and b is unaffected because it refers to a different object.
What identity means
Every object has an identity that stays fixed for its lifetime. In CPython, the reference implementation, id(obj) returns the object's memory address. The expression a is b is equivalent to id(a) == id(b), but it is faster and clearer.
Two objects that are alive at the same time never share an identity. Once an object is garbage collected, a new object may reuse its id. So comparing ids that you saved earlier is not a reliable way to track objects.
The diagram shows that == can end up at identity. The default __eq__ that every class inherits from object compares identity, so two instances of a class with no custom __eq__ are equal only if they are the same object.
Equal values do not imply one object
Do not use is to compare numbers or strings. Whether two equal values are the same object is an implementation detail.
CPython keeps one shared object for small integers (-5 to 256) and interns many short strings that look like identifiers. Other equal values may or may not be shared, depending on how and where they were created.
big1 = int("1000")
big2 = int("1000")
print(big1 == big2) # True, guaranteed
print(big1 is big2) # not guaranteed either way; usually False in CPythonCode that works because of this caching passes your tests and then fails on another input, another Python version, or another implementation. Python 3.8 and later emit a SyntaxWarning for x is 256 or x is "text" to catch this mistake. Treat that warning as a bug report.
Customizing equality
You control == by defining __eq__. A well-behaved __eq__ returns NotImplemented, not False, when it does not know how to compare with the other type. That lets Python try the reflected method on the other operand before giving up.
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) # True
print(p is q) # False
print(p == (1, 2)) # False: both sides return NotImplemented, so identity decides
print(len({p, q})) # 1: equal objects with equal hashes collapse in a setNotice the __hash__ method. When a class defines __eq__ without defining __hash__, Python sets __hash__ to None, and instances become unhashable. This prevents a broken state where equal objects have different hashes. If your objects are mutable, keep them unhashable. If you do define __hash__, equal objects must have equal hashes.
There is no __is__ method. Nothing a class does can change what is returns.
Why None uses is
None is a singleton. The interpreter creates exactly one NoneType instance, so identity is a precise test for it. Using is None has three advantages over == None:
- It cannot be fooled by a custom
__eq__. - It is slightly faster, because it skips a method call.
- It states the intent: you are asking whether the value is the missing-value marker, not whether it behaves equal to it.
Here is a class where == gives the wrong answer:
class Anything:
def __eq__(self, other):
return True
__hash__ = None
thing = Anything()
print(thing == None) # True: the class says it equals everything
print(thing is None) # False: it is not the None objectThis is not only a toy problem. Some libraries overload == to return something other than a plain bool. For example, a NumPy array compared with == produces an array of element-wise results (and recent versions treat array == None element-wise too). Putting that in an if raises a ValueError because the truth value of a multi-element array is ambiguous. array is None always yields a single True or False.
def describe(value=None):
if value is None:
return "nothing supplied"
if value is not None and not value:
return "supplied but falsy"
return "supplied: " + repr(value)
print(describe()) # nothing supplied
print(describe(0)) # supplied but falsy
print(describe([1])) # supplied: [1]Write is not None, not not x is None. Both work, but the first reads as one operator and is the style PEP 8 recommends.
Sentinels beyond None
Sometimes None is itself a legitimate value. For example, None might be a valid default that a caller passes on purpose. The standard fix is a sentinel: a unique object that nobody else can create, tested with is.
_MISSING = object()
def get_or_raise(mapping, key, default=_MISSING):
if key in mapping:
return mapping[key]
if default is _MISSING:
raise KeyError(key)
return default
print(get_or_raise({"a": 1}, "b", None)) # None: caller explicitly asked for None
try:
get_or_raise({}, "b")
except KeyError as e:
print("KeyError:", e) # KeyError: 'b'A fresh object() is equal only to itself, so identity is the right test. The same reasoning explains why the standard library's dict.get can distinguish "no default" from "default is None" internally.
Booleans and is
True and False are also singletons, so x is True is a valid test. It means something different from a truthiness test, though.
for value in [True, 1, 1.0, "yes", [1]]:
print(repr(value), value == True, value is True, bool(value))Output:
True True True True
1 True False True
1.0 True False True
'yes' False False True
[1] False False TrueHere 1 == True because bool is a subclass of int, but 1 is True is false because they are different objects. A non-empty string is truthy but not equal to True. So the three tests give three different answers:
| Test | Question it asks | Passes for `1` | Passes for `"yes"` |
|---|---|---|---|
| `if x:` | Is x truthy? | yes | yes |
| `if x == True:` | Is x numerically equal to 1? | yes | no |
| `if x is True:` | Is x the `True` object? | no | no |
Prefer if x: for normal conditions. Use x is True only when you must separate the real boolean from other truthy values, such as validating a configuration flag that must be a true boolean. Avoid x == True, which has the downsides of both and no advantage.
Containers check identity first
Built-in containers such as lists and tuples compare items with is before they use ==. This shortcut matters when an element does not equal itself, like NaN.
nan = float("nan")
print(nan == nan) # False
print(nan is nan) # True
print([nan] == [nan]) # True: same object, identity shortcut
print([float("nan")] == [float("nan")]) # False: two different NaN objects
print(nan in [nan]) # True: `in` also checks identity firstSo == on a container is not always the same as comparing each element with ==. If you need to detect NaN reliably, use math.isnan(x), not an equality or membership test.
Decision guide
Use these rules in practice:
- Use
is Noneandis not NoneforNone. - Use
isfor your own sentinel objects and for...(Ellipsis) andNotImplemented. - Use
==for values: numbers, strings, containers, and instances of classes that define equality. - Use
isbetween ordinary objects only when you really mean "the same object," for example to check whether a function returned its argument or a copy. - Never use
iswith number or string literals.
Summary
==compares values through__eq__.iscompares object identity and cannot be overridden.- Default
__eq__falls back to identity. A custom__eq__should returnNotImplementedfor unknown types and usually needs a matching__hash__if instances are immutable. None,True,False, and sentinels are singletons, soisis the right test for them.is Noneis immune to overloaded==.- Whether equal numbers or strings are the same object is an implementation detail. Do not depend on it.
- Containers test identity before equality, which is why
[nan] == [nan]can be true whennan == nanis false.
Exercise
A class defines __eq__ so that it always returns True. Given an instance obj, what do obj == None and obj is None return, and which should you use in an if statement that checks for a missing value? Why?
Show answer
obj == None returns True because the custom __eq__ claims equality with everything, while obj is None returns False because obj is not the None object. Use is None. Identity cannot be overridden, so the test is always accurate, and it is also faster.
Exercise
Predict the output, then explain it. nan = float("nan") print([nan] == [nan]) print([float("nan")] == [float("nan")])
Show answer
The output is True then False. List comparison checks identity before equality for each pair of items. In the first line both lists hold the same NaN object, so the identity check passes even though nan == nan is false. In the second line each list holds a different NaN object, so the identity check fails and the == check also returns false.
Exercise
A function has the signature def fetch(key, default=None). A caller wants to pass None as a real default and still have the function raise KeyError when no default is given. Why does this signature fail, and how do you fix it?
Show answer
The function cannot tell "no default given" from "default is None," because both look like None. Fix it by creating a module-level sentinel, _MISSING = object(), using default=_MISSING in the signature, and testing if default is _MISSING: to raise KeyError. Any other value, including None, is then returned as the caller's default.