Programming Search⌘K

Featureintro

Truth value testing

Also called Python truthiness, truthy and falsy, __bool__, __len__ truth value, falsy values.

Any Python object can be tested for truth in if, while, and, or and not. None, False, numeric zeros and empty collections are false. Other objects are true unless __bool__ or __len__ says otherwise.

Language
Python

Synopsis

from decimal import Decimal
from fractions import Fraction

falsy = [None, False, 0, 0.0, 0j, Decimal(0), Fraction(0, 1),
         "", (), [], {}, set(), range(0)]
print([bool(v) for v in falsy].count(False), "of", len(falsy), "are false")
print(bool(" "), bool([0]), bool(0.1), bool(float("nan")))
Output
13 of 13 are false
True True True True

The first list is the list of false built-in objects in Built-in Types. A space, a list that holds a zero and NaN are all true.

Semantics

r1. "Any object can be tested for truth value", for use in an if or while condition or as an operand of the Boolean operations.1

r2. By default an object is true. It is false if its class defines a __bool__() method that returns False, or a __len__() method that returns zero.1 __bool__() is tried first. If it is not defined, __len__() is called, and a class with neither method has only true instances.2 Example: custom-truth.

r3. The false built-in objects are the constants None and False, the zero of any numeric type, and the empty sequences and collections.1 Example: falsy-values.

r4. If __bool__() or __len__() raises an exception, the exception propagates and the object has no truth value. NotImplemented is an example.1 __bool__() "should return False or True".2 Example: bool-must-be-bool.

r5. Operations and built-in functions with a Boolean result return 0 or False for false and 1 or True for true, unless stated otherwise. The exception is or and and, which "always return one of their operands".1 Example: loop-and-default.

Examples

__bool__ wins over __len__, and a plain class is always true (rule r2).

class Box:
    def __init__(self, items):
        self.items = items
    def __len__(self):
        return len(self.items)

class Flag:
    def __bool__(self):
        return False
    def __len__(self):
        return 5

class Plain:
    pass

print(bool(Box([])), bool(Box([1])), bool(Flag()), bool(Plain()))
Output
False True False True

A list as a loop condition runs until the list is empty, and or picks the first true operand (rules r3 and r5).

queue = [3, 1, 2]
taken = []
while queue:
    taken.append(queue.pop())
print(taken)
name = "" or "guest"
print(name)
Output
[2, 1, 3]
guest

Pitfalls

Zero is not "missing"

if not count treats 0 the same as None (rule r3). When 0 is a valid value, test is None.

This code runs but gives a wrong answer on purpose.

def describe(count=None):
    if not count:
        return "no count given"
    return f"count is {count}"

def describe_fixed(count=None):
    if count is None:
        return "no count given"
    return f"count is {count}"

print(describe(0), "|", describe_fixed(0))
Output
no count given | count is 0

__bool__ that returns an int

bool() checks the result type of __bool__ (rule r4).

This code raises TypeError, on purpose.

class Bad:
    def __bool__(self):
        return 1

print(bool(Bad()))

Comparison

A Go if statement chooses a branch "according to the value of a boolean expression".3 A Go condition must have a Boolean type, so if n { with an integer n does not compile, and the test must be written if n != 0 {. Python accepts any object as a condition (rule r1).

References

  1. Built-in Types, Python 3.15 documentation, Truth Value Testing
  2. The Python Language Reference, Python 3.15, 3.3.1. Basic customization, object.__bool__()
  3. The Go Programming Language Specification, If statements

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source