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.

πŸ‘‰ 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.

I like to explore, experiment and write about data science concepts and tools. You can read my articles on Medium. Also, you can connect with me on LinkedIn and Twitter.

Reply

or to participate.