- Daily Dose of Data Science
- Posts
- Use Custom Python Objects In A Boolean Context
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.
Reply