Python – Customize Truth Value testing

We have discussed Truth Value testing in our previous Articles “Python – Truth Value Testing” and “Python – Truth Value Testing for Class objects“. Through this article, we will discuss customizing Truth Value testing.

We can customize Truth value testing by defining __bool__ and __len__ functions. Initially, Python verifies the definition of _bool_ function; if it doesn’t exist, it looks for __len__function. If both the functions are don’t exist, Python always returns True for class objects. We can change this behavior by overloading __bool__ and __len__ functions.

Let’s write a simple example code where these two functions return the False and 0 values respectively to ensure to fail the Truth value testing.

>> class Sample:
...    def __bool__(self):
...       return False
...    def __len__(self):
...       return 0
... 
>>> obj = Sample()
>>> if obj:
...    True
... else:
...    False
... 
False

Observe here, when you attempt to do the Truth Value testing on the class object obj; it always returns the value False.

/Shijit/

Python – Customize Truth Value testing

Leave a Reply

Your email address will not be published.

Scroll to top