Discover more from Daily Dose of Data Science
Use Custom Python Objects In A Boolean Context
Another cool magic method in Python.
In a boolean context, Python always evaluates the objects of a custom class to True. But this may not be desired in all cases. Here's how you can override this behavior.
The __𝐛𝐨𝐨𝐥__ dunder method is used to define the behavior of an object when used in a boolean context. As a result, you can specify explicit conditions to determine the truthiness of an object.
This allows you to use class objects in a more flexible and intuitive way.
As demonstrated above, without the __𝐛𝐨𝐨𝐥__ method (without_bool.py), the object evaluates to True. But implementing the __𝐛𝐨𝐨𝐥__ method lets us override this default behavior (with_bool.py).
Some additional good-to-know details
When we use ANY object (be it instantiated from a custom or an in-built class) in a boolean context, here’s what Python does:
First, Python checks for the __𝐛𝐨𝐨𝐥__ method in its class implementation. If found, it is invoked. If not, Python checks for the __𝐥𝐞𝐧__ method. If found, __𝐥𝐞𝐧__ is invoked. Otherwise, Python returns True.
This explains the default behavior of objects instantiated from a custom class. As the
Cart class implemented neither the __𝐛𝐨𝐨𝐥__ method nor the __𝐥𝐞𝐧__ method, the
cart object was evaluated to True.
Thanks for reading Daily Dose of Data Science! Subscribe for free to learn something new and insightful about Python and Data Science every day.
👉 Read what others are saying about this post on LinkedIn.
👉 Do not forget to react to this post by clicking the ❤️ button.
👉 If you love reading this newsletter, feel free to share it with friends!
Thanks for considering my request in yesterday’s post to leave a ❤️ react. I am truly overwhelmed by the response. I would really appreciate it if you could continue supporting me this way 😇.
Find the code for my tips here: GitHub.