Truthiness of Python Objects

Python
Author

Imad Dabbura

Published

September 1, 2022

When trying to evaluate the truthiness of an object x, basically the following is done in order:

class A:
    ...

class B:
    def __bool__(self):
        print("In __bool__")
        return False

class C:
    def __len__(self):
        print("In __len__")
        return False

class D:
    def __bool__(self):
        print("In __bool__")
        return False

    def __len__(self):
        print("In __len__")
        return False
if A(): print("Truthy")     #=> "Truthy"
if B(): print("Truthy")     #=> "In __bool__"
if C(): print("Truthy")     #=> "In __len__"
if D(): print("Truthy")     #=> "In __bool__"