Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class that returns False with bool(TheClassItself)

I want to create a class MyClass where bool(MyClass) returns False. Is it possible?

I want this behavior with the class itself, not objects of that class. For objects of that class I know that I can just return False in __bool__(self).

like image 950
Eduardo Avatar asked May 27 '18 18:05

Eduardo


1 Answers

To define the __bool__ method used by a class, not its instances, you need to modify its class. You do that by writing a metaclass.

class FalseMeta(type):
    def __bool__(self):
        return False

class MyClass(metaclass=FalseMeta):
    pass

print(bool(MyClass))  # False
like image 151
Olivier Melançon Avatar answered Sep 24 '22 02:09

Olivier Melançon