Sub topic 8
Truthiness of values
This chapter assumes you can run Python code, know the built-in types int, float, str, bool, list and dict, and can assign to variables. It also assumes you know == and is from the comparison chapters. Here you will learn which values count as true or false when Python needs a yes-or-no answer. That knowledge is the basis for and, or and not, which come next.
What truthiness means
Some places in Python need a Boolean (True or False). Examples are the condition of an if or while, the operands of not, and the arguments to bool(). If you pass any other kind of object there, Python converts it. The result is called the object's truthiness. An object that converts to True is truthy. One that converts to False is falsy.
values = [0, 0.0, "", [], {}, set(), None, "0", " ", [0], -1, 0.1]
for v in values:
print(repr(v), bool(v))The first six values and None print False. The rest print True. Notice that "0", " " and [0] are truthy. They are not empty, even though they look empty or "zero-like".
The rule
By default, an object is truthy. A type opts out by saying that some of its values are "empty" or "zero". The built-in falsy values are:
| Type | Falsy value |
|---|---|
| `NoneType` | `None` |
| `bool` | `False` |
| Numbers | `0`, `0.0`, `0j`, `Decimal(0)`, `Fraction(0, 1)` |
| Strings and bytes | `""`, `b""` |
| Sequences | `[]`, `()`, `range(0)` |
| Mappings and sets | `{}`, `set()`, `frozenset()` |
Everything else is truthy. That includes negative numbers, float("nan"), non-empty containers (even if they hold only falsy items), and functions and classes themselves.
How Python decides
For an arbitrary object, Python checks two special methods in order. First it looks for __bool__. If the class defines it, Python uses its result. If not, Python looks for __len__ and treats a length of 0 as false. If neither exists, the object is true.
This is why every empty built-in container is falsy: they all define __len__, and it returns 0.
Idiomatic uses
Testing truthiness directly is the normal Python way to ask "is there anything here?"
items = []
if not items:
print("nothing to process")
name = "Ada"
if name:
print(f"Hello, {name}")This is shorter than if len(items) == 0 and works for any container. Style guides such as PEP 8 recommend it for sequences.
The `None` versus falsy trap
Truthiness lumps None, 0, "" and [] together. Sometimes you need to tell them apart. A common bug is using a truthiness test when the argument can legitimately be 0 or an empty string.
def port_or_default(port=None):
if not port:
return 8080
return port
def port_or_default_fixed(port=None):
if port is None:
return 8080
return port
print(port_or_default(0))
print(port_or_default_fixed(0))The first call prints 8080, which overrides an explicit 0. The second prints 0. Use is None when None means "not provided" and other falsy values are valid. Use plain truthiness when "empty or missing" really are the same case for you.
Strings that look false
Only the empty string is falsy. The text "False", "0" and "no" are all truthy. This matters when you read configuration values or environment variables, which always arrive as strings.
import os
raw = os.environ.get("DEBUG", "0")
print(bool(raw))
print(raw == "1")Here bool(raw) prints True even though the value is "0". If you need a real flag, compare the text explicitly, as in raw == "1", or map accepted spellings such as "true" and "yes" yourself.
Truthiness in your own classes
Define __len__ when your object is a container, and define __bool__ when it has some other notion of "on" or "empty". If both exist, __bool__ wins.
class Basket:
def __init__(self, items):
self.items = list(items)
def __len__(self):
return len(self.items)
class Flag:
def __init__(self, on):
self.on = on
def __bool__(self):
return self.on
print(bool(Basket([])))
print(bool(Basket(["apple"])))
print(bool(Flag(False)))
print(bool(Flag(True)))The output is False, True, False, True. __bool__ must return an actual bool. Returning anything else, such as 1, raises a TypeError when Python converts the object.
Booleans are integers
bool is a subclass of int. True equals 1 and False equals 0 in arithmetic. This gives you a compact way to count how many conditions hold.
print(True + True)
nums = [1, 3, 5, 7]
print(sum(n > 2 for n in nums))
print(any([]), all([]))The three lines print 2, 3 and False True. The built-ins any() and all() use truthiness on each item. any([]) is False because no item is truthy. all([]) is True because no item is falsy, so nothing contradicts the claim.
Common mistakes
- Treating
0as "missing". Useis Nonewhen zero is a valid value. - Assuming a non-empty container with falsy contents is falsy.
[0],[None]and[[]]are all truthy. - Expecting
bool("False")to beFalse. - Writing
if x == True. It fails for truthy values other than1. - Calling
bool()on an object whose__bool__returns a non-bool. - Forgetting that
nanis truthy:bool(float("nan"))isTrue.
Exercises
Exercise
Predict the output of print(bool([[]]), bool([]), bool(" "), bool(0.0)).
Show answer
True False True False. The list [[]] holds one item, so it is not empty. [] is empty. The string " " has one character. 0.0 is zero.
Exercise
A function set_timeout(seconds=None) should use 30 when no value is given but must accept 0 to mean "no timeout". Why does seconds = seconds or 30 fail, and what is the fix?
Show answer
0 is falsy, so seconds or 30 replaces an explicit 0 with 30. The fix is if seconds is None: seconds = 30, which replaces only the missing value.
Exercise
A class defines __len__ returning 5 and __bool__ returning False. What does bool(obj) return, and why?
Show answer
False. Python checks __bool__ first and uses its result. It only falls back to __len__ when __bool__ is not defined.