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)
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With