Truthiness
Truthiness is how Python decides whether a value counts as true or false in an if, while, or and/or expression. Many objects are usable as conditions without an explicit comparison to True.
Detailed Explanation
In an if test Python does not require a boolean. It asks the object whether it wants to be treated as true. The rule is documented and consistent: None, False, 0, 0.0, empty strings, empty bytes, empty containers, and custom objects that say they are empty all count as false. Everything else counts as true.
That is why if items: is the usual way to ask "is there anything in this list?". You are not comparing to True. You are asking the list about its length. An empty list is false. A list with one None in it is true, because it is not empty.
The lookup order is fixed. Python first looks for __bool__. If that method exists, its return value is the answer and it must be a real bool. If it does not exist, Python looks for __len__ and treats a length of zero as false. If neither exists, the object is true. That last rule is why a random class instance is true even when all of its fields are None.
Boolean operators short-circuit and return an operand, not necessarily True or False. a or b returns a if a is true, otherwise b. a and b returns a if a is false, otherwise b. This is the idiom behind name = raw or "anonymous": if raw is a non-empty string you keep it, otherwise you use the default. It is also the source of a common bug. timeout = seconds or 30 treats 0 as missing, so a caller who wanted a zero timeout gets 30.
not always returns a boolean. bool(x) is the explicit conversion and uses the same rule as if x.
Reach for a comparison when the condition is not emptiness. if count: is wrong when 0 is a valid count you must handle. if count is None: and if count > 0: say what you actually mean. Reserve bare truthiness for "is this present and non-empty?".
Custom types should implement __bool__ when they have a natural yes-or-no meaning, such as a connection that is open or closed. They should implement __len__ when they are collections. Implementing both is allowed; __bool__ wins.
Code Examples
# Empty containers are false. A container of false values is still true.
cart = []
print(bool(cart)) # False
if not cart:
print("cart is empty")
cart.append(0)
print(bool(cart)) # True <- one element, even though that element is 0
print(bool(0), bool(""), bool(None), bool({})) # False False False False# `or` and `and` return an operand, not a boolean.
raw_name = ""
display = raw_name or "guest"
print(display) # guest
# Zero is false, so this default fires when the caller meant "no delay".
seconds = 0
timeout = seconds or 30
print(timeout) # 30, probably not what the caller asked for
timeout = 30 if seconds is None else seconds
print(timeout) # 0class Connection:
def __init__(self, open_: bool):
self._open = open_
def __bool__(self) -> bool:
return self._open # `if conn:` means "is it open?"
conn = Connection(False)
print(bool(conn)) # FalseCommon Gotchas
`or` treats `0`, `""`, and `[]` as missing
`value or default` cannot tell "the caller sent zero" from "the caller sent nothing". Use `None` as the sentinel and test with `is None`.
A list of falsy items is still true
`if [None, 0, ""]:` runs the body. Emptiness is about length, not about the elements.
NumPy arrays do not have a boolean value
`if array:` raises `ValueError` because an array has many elements. Use `array.any()` or `array.size`.
`is True` is not truthiness
`if flag is True` rejects `1` and custom objects. Use it only when you must have the exact singleton `True`.