Daily Dose of Data Science

Share this post

Use Custom Python Objects In A Boolean Context

www.blog.dailydoseofds.com

Use Custom Python Objects In A Boolean Context

Another cool magic method in Python.

Avi Chawla
Apr 15, 2023
13
1
Share

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!

Share Daily Dose of Data Science


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.

13
1
Share
Previous
Next
1 Comment
nivedita
Writes niveditaโ€™s Substack
Apr 17

Thank you for providing such awesome content so regularly

Expand full comment
Reply
Top
New
Community

No posts

Ready for more?

ยฉ 2023 Avi Chawla
Privacy โˆ™ Terms โˆ™ Collection notice
Start WritingGet the app
Substackย is the home for great writing