Sub topic 6
Truthiness: using values as conditions
This chapter assumes you can write a basic if/else block and know Python's built-in types: int, float, str, bool, list, dict, and None. It covers how Python turns any value into true or false, when that helps, and when it hides bugs.
Conditions do not have to be booleans
An if statement does not require a bool. Python accepts any object and asks whether it is "truthy" or "falsy".
items = []
if items:
print('has items')
else:
print('empty')This prints empty. The empty list is falsy, so no explicit len(items) > 0 check is needed. Python applies the same rule to while conditions, conditional expressions, not, and, or, and the built-in bool() function.
The falsy values
Most values are truthy. The built-in falsy values are a short list:
| Category | Falsy values |
|---|---|
| Constants | `None`, `False` |
| Zero numbers | `0`, `0.0`, `0j`, `Decimal(0)`, `Fraction(0, 1)` |
| Empty sequences | `''`, `b''`, `[]`, `()`, `range(0)` |
| Empty collections | `{}`, `set()`, `frozenset()` |
Everything else is truthy. Four cases surprise people:
'0'and'False'are truthy. They are non-empty strings.' '(a single space) is truthy for the same reason.[0]and[None]are truthy. The list has one element, and truthiness looks at the container, not its contents.float('nan')is truthy, because it is not equal to zero.
You can check any value with bool():
values = [0, 0.0, 1, -1, '', ' ', 'False', [], [0], {}, (), None]
for v in values:
print(f'{v!r:>8} -> {bool(v)}')How Python decides
Truthiness is not a fixed list inside the interpreter. It follows a protocol that your own classes can join. For an object x, Python tests it in this order:
- If the type defines
__bool__, call it. It must returnTrueorFalse. - Otherwise, if the type defines
__len__, the object is falsy when the length is 0. - Otherwise, the object is truthy.
The built-in falsy values fit this protocol. int defines __bool__ as "not zero", and list has a __len__. None defines __bool__ to return False.
Your own classes follow the same rules:
class Basket:
def __init__(self, items):
self.items = list(items)
def __len__(self):
return len(self.items)
class Switch:
def __init__(self, on):
self.on = on
def __bool__(self):
return self.on
print(bool(Basket([]))) # False: length is 0
print(bool(Basket(['a']))) # True
print(bool(Switch(False))) # False: __bool__ returns False
print(bool(object())) # True: no __bool__, no __len__When a class defines both methods, __bool__ wins.
Idiomatic uses
The Python style guide (PEP 8) recommends testing sequences directly instead of comparing lengths.
names = ['Ada', 'Grace']
# Preferred
if names:
print('first:', names[0])
# Works, but noisier
if len(names) > 0:
print('first:', names[0])Truthiness is also useful for text input, where an empty string means "nothing entered":
nickname = input('Nickname (optional): ').strip()
if nickname:
print(f'Hello, {nickname}!')
else:
print('Hello, stranger!')You can use it to guard a lookup, which avoids a KeyError when the dictionary is empty:
settings = {}
if settings and settings['debug']:
print('debug on')
else:
print('debug off')This works because and stops as soon as settings is falsy. A later chapter explains that short-circuit behavior in detail. Note also that settings and settings['debug'] would still raise KeyError if settings is non-empty but lacks the 'debug' key. Truthiness tests the container, not the key.
Do not compare with True or False
Beginners often write if flag == True:. Avoid it. bool is a subclass of int, so True == 1, but other truthy values are not equal to True:
x = 2
if x == True:
print('equal to True') # does not run: 2 != 1
if x:
print('truthy') # runsIf you really need to know that something is exactly the boolean True, use identity: if x is True:. That is rare. In most code, write if x:.
Pitfall 1: zero is not the same as missing
Truthiness collapses several different situations into one. 0, '', [], and None are all falsy, but they mean different things. A count of zero is a real answer, while None means no answer was given.
def set_volume(level=None):
if not level:
level = 50
return level
print(set_volume()) # 50
print(set_volume(0)) # 50 -- bug: the caller asked for silenceWhen None is the "not provided" marker, test for it explicitly:
def set_volume(level=None):
if level is None:
level = 50
return level
print(set_volume()) # 50
print(set_volume(0)) # 0This is why the spine's earlier example separates if not count: ("zero or missing") from if count is None: ("missing"). Choose the test that matches what you mean.
Pitfall 2: strings that look like booleans
Text read from files, environment variables, or forms is always a string. A non-empty string is truthy, whatever it says.
import os
raw = os.environ.get('FEATURE_ENABLED', 'False')
if raw:
print('always runs, even for "False" and "0"')
enabled = raw.strip().lower() in ('1', 'true', 'yes', 'on')
print(enabled)Convert the text to a real boolean once, near where it enters your program. Then use if enabled: everywhere else. The membership test with in is covered in a later chapter.
Pitfall 3: containers whose truthiness is ambiguous
Some libraries refuse to define a single answer. A NumPy array with more than one element raises ValueError: The truth value of an array with more than one element is ambiguous when used in an if. In that case you must choose .any() or .all() explicitly. The lesson is general: truthiness is a convention that each type implements, so check the documentation for non-built-in types.
Pitfall 4: filtering by truthiness removes real zeros
Truthiness is often used to clean up data, and the same trap appears there.
readings = [3, 0, 7, None, 0, 5]
print([r for r in readings if r]) # [3, 7, 5]
print([r for r in readings if r is not None]) # [3, 0, 7, 0, 5]The first version drops the valid zero readings along with None. The second removes only the missing values. The built-in filter(None, readings) behaves like the first version.
Pitfall 5: a falsy return value that means "success"
A function that returns 0 for success follows an old C convention. if run(): then reads backwards, because 0 is falsy. Prefer returning a bool or raising an exception. If you inherit such a function, compare the result explicitly: if run() == 0:.
Writing your own `__bool__` safely
Define __bool__ only when "truth" has an obvious meaning for the type, such as "has any content" or "is enabled". Two rules keep it safe:
- Return a real
bool. Returning anything else raisesTypeError. - Keep it cheap and free of side effects, since it can run at any
if.
If a type has no natural truth value, leave both methods out and every instance will be truthy. That is acceptable, but it means if obj: can never catch a problem, so test for None explicitly.
Summary
- Any object can be a condition. Python uses
__bool__, then__len__, then defaults to truthy. - The built-in falsy values are
None,False, numeric zeros, and empty strings, sequences, and collections. - Prefer
if items:overif len(items) > 0:, andif flag:overif flag == True:. - Use
is Nonewhen zero or empty is a valid value. - Convert strings such as
'False'to real booleans before testing them.
Exercise
What does this code print, and why? def label(n=None): then if n: return 'positive-ish', elif n is None: return 'missing', else: return 'zero'. Calls: label(5), label(0), label(None), label(-3).
Show answer
It gives 'positive-ish', 'zero', 'missing', 'positive-ish'. The first branch tests plain truthiness, so any non-zero number, including -3, is truthy and takes it. For 0, the first test fails and 0 is not None, so the else branch runs. For None, the first test fails and the elif catches it. Because the first branch already handles every truthy value, the order matters: if the n is None test came after an else, it would never be reached.
Exercise
A config loader returns a dict. You want to apply a default timeout of 30 only when the "timeout" key is absent or None, but keep a timeout of 0 (meaning "no waiting"). Which test is correct: if not config.get('timeout'): or if config.get('timeout') is None:?
Show answer
Use if config.get('timeout') is None:. The .get() call returns None for a missing key, so both the "absent" and "None" cases match. The not version would also replace a legitimate timeout of 0 with 30, because 0 is falsy.