3

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.

Dimitris Fasarakis Hilliard
  • 119,766
  • 27
  • 228
  • 224
Olian04
  • 4,754
  • 2
  • 23
  • 46

3 Answers3

6

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)
...
>>>
TigerhawkT3
  • 44,764
  • 6
  • 48
  • 82
  • 1
    @richard - Failure to understand code is not an appropriate reason to edit it. These "confusing and irrelevent chevrons, elipses" are from an interactive interpreter session. – TigerhawkT3 Nov 22 '16 at 18:05
  • I have used ipython, as well. I have also seen my pupils type in the chevrons. – ctrl-alt-delor Nov 22 '16 at 18:06
  • @richard - The question is explicitly tagged with Python 3, and contains a Python 3-style `print()` call (which technically works in Python 2, but is much more likely to appear in Python 3). – TigerhawkT3 Nov 22 '16 at 18:10
  • @richard - Also, http://stackoverflow.com/questions/8909932/how-to-overload-pythons-bool-method. – TigerhawkT3 Nov 22 '16 at 18:12
  • There is nothing non python2 about that print call, and I put in the comment to help anyone that comes after me, not to start an argument. – ctrl-alt-delor Nov 22 '16 at 18:15
2

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.

Dimitris Fasarakis Hilliard
  • 119,766
  • 27
  • 228
  • 224
1

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.

Daniel
  • 39,063
  • 4
  • 50
  • 76