From the documentation https://docs.python.org/2/reference/datamodel.html#object.nonzero:
object.__nonzero__(self)
Called to implement truth value testing and the built-in operation bool()
; should return False
or True
, or their integer equivalents 0
or 1
. When this method is not defined, __len__()
is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither __len__()
nor __nonzero__()
, all its instances are considered true.
And for Python 3 https://docs.python.org/3.7/reference/datamodel.html#object.nonzero:
object.__bool__(self)
Called to implement truth value testing and the built-in operation bool()
; should return False
or True
. When this method is not defined, __len__()
is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither __len__()
nor __bool__()
, all its instances are considered true.
Try:
class MyList(list):
def __bool__(self):
return True
print(bool(list([])))
if list([]):
print('This does not print')
print(bool(MyList([])))
if MyList([]):
print('This prints')