Sub topic 6
Truth value and numeric conversions
This chapter covers the special methods behind bool(), if obj:, int(), float() and indexing. It assumes you can write a class with __init__ and regular methods, and that you know __len__ from the data model overview. The __bool__ and __len__ methods decide truthiness. __int__, __float__ and __index__ convert an object to a number.
How Python decides truthiness
Every object has a truth value. Python uses it in if, while, and, or, not and in bool(obj). Python checks the object's type in a fixed order:
- If the type defines
__bool__, call it and use the result. - Otherwise, if the type defines
__len__, the object is true when the length is not zero. - Otherwise, the object is always true.
The Vector class from the arithmetic example uses step 1:
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __bool__(self):
return bool(self.x or self.y)
print(bool(Vector(0, 0))) # False
print(bool(Vector(0, 3))) # TrueA class that defines only __len__ uses step 2. This is why empty lists and strings are false:
class Basket:
def __init__(self, items):
self.items = list(items)
def __len__(self):
return len(self.items)
print(bool(Basket([]))) # False
print(bool(Basket(['apple']))) # TrueIf a class defines both methods, __bool__ wins. The class below has length 0 and is still true:
class Both:
def __len__(self):
return 0
def __bool__(self):
return True
print(bool(Both())) # True
print(len(Both())) # 0Define __bool__ when "empty" or "zero" does not match the length, or when computing the length is expensive. A __bool__ that checks a cheap flag avoids a full count.
Rules and gotchas
__bool__ must return a real bool. Returning 1 or None raises TypeError:
class Bad:
def __bool__(self):
return 1
try:
bool(Bad())
except TypeError as e:
print(e) # __bool__ should return bool, returned intPython looks up special methods on the type, not on the instance. Assigning __bool__ to one object has no effect:
class Flag:
pass
f = Flag()
f.__bool__ = lambda: False
print(bool(f)) # TrueThe truth value is also separate from the other conversions. A class that defines __int__ but not __bool__ is still always true, even when int(obj) is 0.
Numeric conversions
Three methods convert an object to a built-in number. Each must return the exact built-in type.
| Call | Method | Must return |
|---|---|---|
| `int(obj)` | `__int__` | `int` |
| `float(obj)` | `__float__` | `float` |
| `complex(obj)` | `__complex__` | `complex` |
| `operator.index(obj)`, `seq[obj]`, `hex(obj)` | `__index__` | `int` |
float(obj) calls __float__. Functions in math that expect a real number use the same hook:
import math
class Celsius:
def __init__(self, degrees):
self.degrees = degrees
def __float__(self):
return float(self.degrees)
def __int__(self):
return int(self.degrees)
t = Celsius(21.5)
print(float(t)) # 21.5
print(int(t)) # 21
print(math.sqrt(Celsius(16))) # 4.0int() is for explicit conversion, and it may lose information. Here int(t) truncates 21.5 to 21. Defining these methods does not add arithmetic. Celsius(1) + 1 raises TypeError until you also write __add__.
`__index__`: exact integers only
__index__ has a narrower job than __int__. Python calls it where only a true integer makes sense: list indexes, slice bounds, range(), bin(), hex() and oct(). Because Python calls it implicitly, it must never lose information.
class Slot:
def __init__(self, n):
self.n = n
def __index__(self):
return self.n
items = ['a', 'b', 'c', 'd']
s = Slot(2)
print(items[s]) # c
print(items[:s]) # ['a', 'b']
print(hex(Slot(255))) # 0xff
print(bin(Slot(5))) # 0b101
print(list(range(Slot(3)))) # [0, 1, 2]This is why a float cannot index a list, even when it holds 2.0. A float has __int__ but no __index__. Define __index__ only for types that really are integers, such as an enum-like ID or a bit-flag class.
Since Python 3.8, int() and float() fall back to __index__ when __int__ or __float__ is missing. So int(Slot(7)) gives 7 and float(Slot(7)) gives 7.0. If you define __index__, you rarely need to define __int__ as well.
Choosing what to define
- Give a container
__len__and let truthiness follow from it. - Add
__bool__when "empty" means something other than length zero. - Add
__float__for types that wrap a measurement, such as a temperature or a price. - Add
__int__only if truncation is a sensible meaning for your type. - Add
__index__only for exact integer types. - Return the exact built-in type from each method.
TypeErroris the penalty otherwise.
Exercise
A class defines __len__ returning 3 and __bool__ returning False. What do len(obj) and bool(obj) return, and why?
Show answer
len(obj) returns 3 and bool(obj) returns False. len() calls __len__ directly. For truthiness, Python checks __bool__ first and only falls back to __len__ when __bool__ is missing.
Exercise
The class Meters defines __float__ and __int__ but not __index__. Why does [10, 20, 30][Meters(1.0)] raise TypeError, and what would you add if Meters always held a whole number and you wanted this to work?
Show answer
Indexing calls __index__, not __int__ or __float__, because an implicit conversion must be exact. Without __index__ Python refuses to guess. If Meters always held a whole number, add def __index__(self): return int(self.value), and the lookup returns 20.