Sub topic 13
Customizing truthiness and equality in your classes
This chapter assumes you can write a Python class with __init__ and methods. It also assumes you know how truthiness, ==, and is work for built-in types. Here you will control what if obj: and a == b mean for your own objects.
How Python decides if an object is true
When Python needs a truth value, it asks the object in a fixed order. This happens in if, while, not, and, or, and bool().
An instance of a plain class is always true. You only change that by defining one of the two methods.
Defining `__bool__` and `__len__`
Use __len__ when your object is a container and "empty" should mean false. Use __bool__ when truth means something else, such as "is valid" or "is enabled".
class Basket:
def __init__(self, items):
self.items = list(items)
def __len__(self):
return len(self.items)
class Flag:
def __bool__(self):
return False
print(bool(Basket([])), bool(Basket([1]))) # False True
print(bool(Flag())) # False__bool__ must return a real bool. If it returns anything else, such as 0 or None, Python raises TypeError. If you define both methods, __bool__ wins and __len__ is not consulted for truth.
Defining `__eq__`
By default, == on your objects behaves like is. Two separate instances with identical data are not equal. Define __eq__ to compare by value.
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))
a = Point(1, 2)
b = Point(1, 2)
print(a == b) # True
print(a is b) # False
print(a != b) # False
print(a == (1, 2)) # False
print(len({a, b})) # 1Three details matter here:
- Return
NotImplementedfor foreign types. This is a special value, not an exception. It tells Python to try the other operand's__eq__. If neither side can compare, Python falls back to identity, soa == (1, 2)isFalseand does not raise an error. !=comes for free. Python 3 derives__ne__by inverting__eq__, so you rarely write it.- Equality and hashing go together. If you define
__eq__without__hash__, Python sets__hash__toNone. Your objects then become unhashable and cannot go in sets or serve as dict keys.
Keeping equality and hash consistent
The rule is that objects that compare equal must have equal hashes. Build the hash from the same fields that __eq__ compares, as Point does above. If those fields can change after the object is in a set or dict, the object will be stored under the wrong hash and lookups will fail. Either treat such objects as immutable or leave them unhashable.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| `__bool__` returns `0` or `1` | `TypeError` | Return `True` or `False` |
| `__eq__` with no `__hash__` | `TypeError: unhashable type` in sets and dicts | Define `__hash__` from the same fields |
| `__eq__` raises on other types | `a == 5` crashes | Return `NotImplemented` |
| Testing optional arguments with `if obj:` | Empty or falsy objects look missing | Use `is None` |
Exercise
A class Queue defines __len__ but not __bool__. After q = Queue() with no items, what do bool(q) and q is None return? Why does this matter when you write def run(q=None): q = q or Queue()?
Show answer
bool(q) is False because __len__ returns 0, and q is None is False because q is a real object. In run, passing an empty Queue makes q or Queue() discard it and create a new one, which is a bug. Write if q is None: q = Queue() instead.
Exercise
You write a Money class with __eq__ comparing amount and currency, and then try {Money(5, "USD")}. What error do you get, and how do you fix it?
Show answer
You get TypeError: unhashable type: 'Money', because defining __eq__ without __hash__ sets __hash__ to None. Add def __hash__(self): return hash((self.amount, self.currency)).