__bool__

Dunder MethodPython 2.0+Intermediate

Called by bool(); defines truthiness of the object

Quick Info

Documentation
Official Docs
Python Version
2.0+

Learn by Difficulty

Quick Example

python
class NonEmpty:
    def __init__(self, items):
        self.items = items

    def __bool__(self):
        return len(self.items) > 0

a = NonEmpty([1, 2, 3])
b = NonEmpty([])
print(bool(a))
print(bool(b))
if a:
    print("a is truthy")

__bool__ called by bool(); defines truthiness of the object. Implementing it lets you customize how Python interacts with your objects.

Try in Playground

Tags

oopmagic-methodprotocolcore