Search code examples
pythonpython-3.xclasswhile-loopoperation

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.


Solution

  • 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)
    ...
    >>>