Bool Operation Problem

Consider following code

class A:
    def __bool__(self):
        print("a")
        return True

class B:
    def __bool__(self):
        print("b")
        return True
class C:
    def __bool__(self):
        print("c")
        return True

A() and B() and C()

I think it should print

a
b
c

But it prints

a
b

WHY?

Why should it care about the truth value of C()? What decision would that affect?

I think the program first evaluates A() and B(), gets a True, then evaluates True and C(). That is why I think the truth value of C() should be cared.

In the first case the result of the expression is your instance C(). It is just a value, and does not need to be evaluated as a bool.

In [1]: class A:
   ...:     def __bool__(self):
   ...:         print("a")
   ...:         return True
   ...: 
   ...: class B:
   ...:     def __bool__(self):
   ...:         print("b")
   ...:         return True
   ...: class C:
   ...:     def __bool__(self):
   ...:         print("c")
   ...:         return True
   ...: 
   ...: A() and B() and C()
a
b
Out[1]: <__main__.C at 0x7f8847e1ecf0>

If you then use that in a boolean context:

In [2]: class A:
   ...:     def __bool__(self):
   ...:         print("a")
   ...:         return True
   ...: 
   ...: class B:
   ...:     def __bool__(self):
   ...:         print("b")
   ...:         return True
   ...: class C:
   ...:     def __bool__(self):
   ...:         print("c")
   ...:         return True
   ...: 
   ...: bool(A() and B() and C())
a
b
c
Out[2]: True
3 Likes

Now I understand. Thanks

It does need to check the truth values of A() and B() in order to know whether it’s done or has to continue evaluating. But nothing depends on the truth value of C().

The doc:

The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

If bool(x) is True, y is returned, not bool(y). Similarly for x or y when bool(x) is False.