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.
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.
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)
...
>>>
The while
statement is composed of the while
keyword followed by an expression.
When an expression is used in a control flow statement the truth value of that expression is evaluated by calling the objects __bool__
method:
In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false:
False
,None
, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true. User-defined objects can customize their truth value by providing a__bool__()
method.
In short, the result depends on what the __bool__
of your object returns; since you haven't specified one, a default value of True
is used.
There are different methods, that can be called, to determine, whether an object evaluates to True
or False
.
If a __bool__
-method is defined, this is called, otherwise, if __len__
is defined, its result is compared to 0
.