yunline
(云line)
December 12, 2024, 12:53pm
1
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?
Stefan2
(Stefan)
December 12, 2024, 12:58pm
2
Why should it care about the truth value of C()
? What decision would that affect?
yunline
(云line)
December 12, 2024, 1:03pm
3
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.
effigies
(Chris Markiewicz)
December 12, 2024, 1:04pm
4
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
Stefan2
(Stefan)
December 12, 2024, 1:06pm
6
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()
.
tjreedy
(Terry Jan Reedy)
December 20, 2024, 6:31pm
7
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.