Sub topic 6
Truth value and numeric conversions
This chapter assumes you can define classes with __init__ and regular methods, and that you know Python's built-in numeric types. It covers the special methods Python calls for if obj:, int(obj), float(obj), and for places that need a true integer, such as indexing.
How Python decides truthiness
When you write if obj: or while obj:, Python asks the object's type for its truth value. It follows this order:
- If the class defines
__bool__, Python calls it. It must return abool. - Otherwise, if the class defines
__len__, Python calls it. A length of 0 is false, and any other length is true. - Otherwise, the object is always true.
Step 3 surprises people. A plain class with no __bool__ or __len__ is always truthy, even if it looks "empty" to you.
class Basket:
def __init__(self, items):
self.items = list(items)
def __len__(self):
return len(self.items)
class Wallet:
def __init__(self, cents):
self.cents = cents
def __bool__(self):
return self.cents > 0
print(bool(Basket([]))) # False, falls back to __len__
print(bool(Basket([1]))) # True
print(bool(Wallet(0))) # False
print(bool(Wallet(250))) # TrueDefine __bool__ when "empty" or "zero" has a meaning that differs from length. If you define both, __bool__ wins.
Numeric conversions
Three methods hook into the built-in conversion functions.
| Call | Method | Must return |
|---|---|---|
| `int(obj)` | `__int__` | an `int` |
| `float(obj)` | `__float__` | a `float` |
| `operator.index(obj)` | `__index__` | an `int` |
__int__ and __float__ are explicit conversions. Python never applies them silently, so [10, 20][Money(1)] does not call __int__.
__index__ is different. It says "this object is losslessly an integer". Python uses it wherever it needs a real integer: list indexes, slices, range(), hex(), bin() and oct(). Implement it only for integer-like types, not for anything that rounds.
class Money:
def __init__(self, cents):
self.cents = cents
def __int__(self):
return self.cents // 100 # truncates to whole dollars
def __float__(self):
return self.cents / 100
class Slot:
def __init__(self, number):
self.number = number
def __index__(self):
return self.number
m = Money(1999)
print(int(m)) # 19
print(float(m)) # 19.99
shelf = ['a', 'b', 'c', 'd']
s = Slot(2)
print(shelf[s]) # c
print(hex(Slot(255))) # 0xffIf a class defines __index__ but not __int__, int(obj) still works, because Python falls back to __index__.
Exercise
A class defines __len__ returning 0 and __bool__ returning True. What does bool(obj) return, and why?
Show answer
True. Python checks __bool__ first and only falls back to __len__ when __bool__ is missing.
Exercise
You write a Temperature class with __float__. Why does [1, 2, 3][Temperature(1.0)] fail, and what would make it work?
Show answer
Indexing needs __index__, and Python does not use __float__ or __int__ implicitly. Adding __index__ returning an int would make it work, but only do that if the object really is an integer.