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.ja va2  s  . c  om
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  w  w. j  av a2  s . c  o  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 
#  ww w .  ja  va  2  s.  co  m
X = Truth() 
if X: print('yes!')

Result

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

Demo

class Truth: 
    pass # from  w  w  w  .j  ava 2  s.c o  m

X = Truth() 
bool(X)