Sub topic 13
Customizing Truthiness and Equality in Your Classes
This chapter assumes you know how truthiness, ==, is, and None checks work for built-in types. Here you apply those rules to your own classes. You will control what if obj: does and what obj == other means. You will also see how those choices interact with None checks, hashing, and containers.
How Python decides whether an object is true
When you write if obj:, while obj:, not obj, or bool(obj), Python runs a fixed lookup on the object's class:
- If the class defines
__bool__, call it and use the result. - Otherwise, if the class defines
__len__, call it. A length of 0 is false and any other length is true. - Otherwise the object is true.
Here are the two hooks from the spine, one class for each:
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())) # FalseBasket becomes falsy when empty because of __len__. Flag is always false because of __bool__.
Which hook wins
__bool__ takes precedence over __len__. If a class defines both, __len__ is never consulted for truth testing:
class Both:
def __bool__(self):
return True
def __len__(self):
return 0
print(bool(Both())) # True
print(len(Both())) # 0Define __bool__ when "emptiness" does not describe your object, or when the answer is not a size. Examples are a zero amount of money, a disabled feature, or a connection that has been closed. Define only __len__ when your class is a collection, so that if basket: reads like it does for lists.
Return types are checked
__bool__ must return a real bool. Returning 1 or "yes" raises an error. __len__ must return a non-negative integer, and a negative one raises ValueError.
class Bad:
def __bool__(self):
return 1
try:
bool(Bad())
except TypeError as e:
print("TypeError:", e) # TypeError: __bool__ should return bool, returned intIf the value comes from an expression that might not be a bool, wrap it in bool(...) before returning it.
and, or, and not use the hook but keep the operand
Recall that and and or return one of their operands. The truth hook decides which operand, but your object itself is what comes back:
class Noisy:
def __bool__(self):
print("__bool__ called")
return True
n = Noisy()
result = n or "fallback"
print(result is n) # TrueThe output is __bool__ called followed by True. The hook ran once to make the decision, and result is the original object, not the bool value. not n also calls __bool__, but it always returns a real True or False.
How == works by default
If you define nothing, == on your own objects falls back to identity. Two objects are equal only if they are the same object:
class Plain:
pass
a = Plain()
b = Plain()
print(a == a) # True
print(a == b) # FalseFor value-like classes, such as points, money, or version numbers, you usually want equality by content. You get that by defining __eq__.
Writing __eq__
__eq__(self, other) is called for self == other. A careful implementation checks the type of other and returns the special value NotImplemented when it does not know how to compare:
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))
def __repr__(self):
return f"Point({self.x}, {self.y})"
print(Point(1, 2) == Point(1, 2)) # True
print(Point(1, 2) is Point(1, 2)) # False
print(Point(1, 2) != Point(1, 3)) # True
print(Point(1, 2) == (1, 2)) # False
print(len({Point(1, 2), Point(1, 2)})) # 1Several things happen here:
NotImplementedis not an error and notFalse. It tells Python "I can't answer, ask the other side." Python then tries the reflected operation onother. If both sides returnNotImplemented,==falls back to an identity comparison. That is whyPoint(1, 2) == (1, 2)ends upFalse.- You do not need to write
__ne__. By default!=calls__eq__and inverts the result, unless it isNotImplemented. isis unaffected. You cannot customize it, and it still compares identity.- If the right operand's class is a subclass of the left operand's class and overrides the reflected method, Python tries the right operand first. This lets subclasses take precedence in mixed comparisons.
__eq__ and __hash__ belong together
Objects used as dictionary keys or set members need a hash, and equal objects must have equal hashes. Python protects you from breaking this rule by accident. If a class defines __eq__ without __hash__, Python sets __hash__ to None, and the class becomes unhashable:
class Tag:
def __init__(self, name):
self.name = name
def __eq__(self, other):
if not isinstance(other, Tag):
return NotImplemented
return self.name == other.name
try:
{Tag("a")}
except TypeError as e:
print("TypeError:", e) # TypeError: unhashable type: 'Tag'You have two correct options:
- Leave the class unhashable, which is the right choice for mutable objects.
- Define
__hash__from the same fields that__eq__compares, asPointdoes. Treat those fields as read-only after construction. If you changexon aPointthat sits in a set, the object is stored under a stale hash and lookups can fail.
Equality and None checks
A permissive __eq__ makes == None misleading. The is operator cannot be overridden, so it always tells the truth:
class Anything:
def __eq__(self, other):
return True
obj = Anything()
print(obj == None) # True
print(obj is None) # FalseThis is the strongest reason to write is None and is not None even for classes you own. A well-behaved __eq__ returns NotImplemented for None, but you cannot count on every library class doing so.
Truthiness and None are different questions
Once your class defines __bool__ or __len__, a valid object can be falsy. Then if obj: no longer means "was an object provided?" Here is a Money class where zero is falsy:
class Money:
def __init__(self, cents):
self.cents = cents
def __bool__(self):
return self.cents != 0
def __eq__(self, other):
if not isinstance(other, Money):
return NotImplemented
return self.cents == other.cents
def __hash__(self):
return hash(self.cents)
def describe(balance=None):
if balance is None:
return "unknown"
if not balance:
return "zero"
return f"{balance.cents} cents"
print(describe()) # unknown
print(describe(Money(0))) # zero
print(describe(Money(250))) # 250 centsIf describe began with if not balance:, it would report Money(0) and a missing balance as the same thing. The same mistake appears with default arguments. balance = balance or Money(100) silently replaces an explicit Money(0). Use if balance is None: whenever "missing" and "empty or zero" mean different things.
Containers compare by identity first
Lists, tuples, and dicts compare their elements with an identity check before ==. An element that is the same object is treated as equal even if its __eq__ would say otherwise:
class NeverEqual:
def __eq__(self, other):
return False
__hash__ = None
x = NeverEqual()
print(x == x) # False
print([x] == [x]) # True
print([x] == [NeverEqual()]) # False
nan = float("nan")
print(nan == nan) # False
print([nan] == [nan]) # TrueThis is the same mechanism behind the NaN pitfall from earlier. It also shows that an __eq__ that violates reflexivity (x == x is false) gives results that differ between direct comparison and comparison inside containers. Keep x == x true for your own classes unless you have a strong reason, as NaN does.
Ordering and dataclasses
To support <, <=, >, and >=, define __lt__ and the others. The standard library decorator functools.total_ordering fills in the rest if you supply __eq__ and one ordering method. As with ==, return NotImplemented for foreign types. Python then raises TypeError, as it does for None < 1.
For plain data holders, a dataclass writes __eq__ for you:
from dataclasses import dataclass
@dataclass(frozen=True)
class Version:
major: int
minor: int
print(Version(1, 2) == Version(1, 2)) # True
print(Version(1, 2) == (1, 2)) # False
print(hash(Version(1, 2)) == hash(Version(1, 2))) # TrueThe generated __eq__ compares the fields as tuples, but only when both objects have exactly the same class. With frozen=True and eq=True, it also generates __hash__. With eq=True and frozen=False, which is the default, the class is unhashable, which follows the rule from the hashing section. A dataclass does not define __bool__, so its instances are always true.
Summary of the hooks
| You want | Define | Notes |
|---|---|---|
| `if obj:` to depend on a size | `__len__` | Must return an `int` that is 0 or greater |
| `if obj:` to depend on state | `__bool__` | Must return a real `bool`; wins over `__len__` |
| Equality by value | `__eq__` | Return `NotImplemented` for unknown types |
| Use as a dict key or set member | `__hash__` | Must agree with `__eq__`; defining `__eq__` alone removes it |
| `x is None` to work reliably | Nothing | `is` cannot be overridden |
Exercises
Exercise
A class defines __len__ returning 0 and __bool__ returning True. What does bool(obj) return, and what does len(obj) return?
Show answer
bool(obj) returns True because __bool__ takes precedence over __len__ for truth testing. len(obj) still returns 0 because len() calls __len__ directly.
Exercise
You write a Money class with __eq__ but no __hash__, then try to use Money(5) as a dictionary key. What happens, and what are two ways to fix it?
Show answer
A TypeError: unhashable type: 'Money' is raised, because defining __eq__ without __hash__ sets __hash__ to None. Either define __hash__ from the same fields __eq__ compares, for example hash(self.cents), and treat those fields as read-only. Or use @dataclass(frozen=True), which generates both methods.
Exercise
A function has the parameter timeout=None and starts with timeout = timeout or 30. A caller passes a Duration(0) object whose __bool__ returns false for zero. What goes wrong, and how do you fix it?
Show answer
Duration(0) is falsy, so or discards it and the timeout becomes 30, silently overriding the caller's explicit zero. Test for None with if timeout is None: timeout = 30, which replaces only a missing value.