Special Method Protocols

__bool__() — object lifecycle protocol

Define truth testing for bool(), if and while. Return an actual bool. If absent, __len__ supplies truth testing; if neither exists, instances are truthy.

Formal Syntax & Structure

python syntaxpython
def __bool__(self):

Return Value

bool

Truth value.

Working Example

Example Snippetpython
class Queue:    def __init__(self, items): self.items = items    def __bool__(self): return bool(self.items)print(bool(Queue([])))
Python Reference