hi im Bacon
hi im Bacon

Reputation: 344

Python - How to declare when an instance is True or False

I'm overwriting the MutableSet from collections.abc, and I want to be able to determine whenever its instance equates to True/False.

I know about the magic methods for comparisons, but I am looking for behaviour like checking an empty set/list that Python provides.

class Example():
    pass

e = Example()

if e:
    print("This shall work - the default of an instance is True")

# What I'd like is something similar to...

if []:
    pass
else:
    print("This shall be false because it's empty, there wasn't a comparison")

I've looked in the cookbook: Special methods Data model - Other various websites - I can't seem to find the answer :(

Ultimately I would like to be able to go:

class A:
    def __init__(self, value: int):
        self.value = value

    def __cool_equality_method__(self):
        return self.value > 5

a = A(10)
b = A(3)

if a:
    print("This happens")
if b:
    print("This doesn't happen")

Upvotes: 2

Views: 94

Answers (2)

Djaouad
Djaouad

Reputation: 22766

You need to implement the __bool__ method on your class, which is simply your old __cool_equality_method__ renamed to __bool__:

class A:
    def __init__(self, value: int):
        self.value = value

    def __bool__(self):
        return self.value > 5

a = A(10)
b = A(3)

if a:
    print("This happens")
if b:
    print("This doesn't happen")

"""
This happens
"""

Upvotes: 1

Cedric H.
Cedric H.

Reputation: 8298

What about __bool__ simply?

class A:
    def __bool__(self):
        if not getattr(self, 'trueish', None):
            return False
        else:
            return True

a = A()
if a:
    print("Hello")
a.trueish = True
if a:
    print("a is True")

Upvotes: 2

Related Questions