Python class that returns False with bool(TheClassItself)

  • A+

I want to create, in Python 3, 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 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: