Python - Boolean Tests: __bool__ and __len__

Introduction

Every object is inherently true or false in Python.

Python first tries __bool__ to obtain a direct Boolean value.

If that method is missing, Python tries __len__ to infer a truth value from the object's length.

Demo

class Truth: 
   def __bool__(self): return True 

X = Truth() # from  w w  w.j a  v  a2 s . com
if X: print('yes!') 
class Truth: 
   def __bool__(self): return False 

X = Truth() 
bool(X)

Result

If __bool__ method is missing, Python falls back on length because a nonempty object is considered true:

Demo

class Truth: 
   def __len__(self): return 0 

X = Truth() # from   w  ww  .j a  v a 2  s  . co  m
if not X: print('no!')

Result

If both methods are present Python prefers __bool__ over __len__:

Demo

class Truth: 
   def __bool__(self): return True            # 3.X tries __bool__ first 
   def __len__(self): return 0                # 2.X tries __len__ first 
# from   w ww. j av a2 s . c o  m
X = Truth() 
if X: print('yes!')

Result

If neither truth method is defined, the object is considered true:

Demo

class Truth: 
    pass #  w  w w .jav  a2 s  .  c  o m

X = Truth() 
bool(X)