If statements in Python allow you to do something like:
if not x:
print "X is false."
This works if you’re using an empty list, an empty dictionary, None, 0, etc, but what if you have your own custom class? Can you assign a false value for that class so that in the same style of conditional, it will return false?
Since Python 3, you need to implement the
__bool__method on your class. This should return True or False to determine the truth value:If
__bool__has not been defined, the implementation will call__len__and the instance will be considered True if it returned a nonzero value. If__len__hasn’t been defined either, all instances will be considered True.For further reading:
In Python 2, the special method
__nonzero__was used instead of__bool__.