Olian04 Olian04 - 17 days ago 8
Python Question

What operation is called on A in "while A:"?

Lets say i have:

class Bar:
pass
A = Bar()

while A:
print("Foo!")


What operation is then called on A in order to determine the
while loop
?

I've tried
__eq__
but that didn't do much.

Answer

User-defined objects are truthy, unless you define a custom __bool__:

>>> class A:
...     pass
...
>>> a = A()
>>> if a: print(1)
...
1
>>> class B:
...     def __bool__(self):
...         return False
...
>>> b = B()
>>> if b: print(1)
...
>>>