Wednesday, June 18, 2025

What happens if you don’t implement __bool__ in a class?

All Questions From This Chapter

If you don’t implement __bool__ in a Python class, Python falls back to another method to determine the truthiness of your object.

πŸ” Fallback Behavior:

  1. If __bool__ is not defined, Python checks for __len__.

  2. If __len__ is defined:

    • if obj: will evaluate to False if len(obj) == 0.

    • Otherwise, it evaluates to True.

  3. If neither __bool__ nor __len__ is defined, the object is considered truthy by default (i.e., True).


πŸ” Example Without __bool__:

python
class Empty: def __len__(self): return 0 e = Empty() print(bool(e)) # False, because __len__ returns 0

🧱 Example With Neither:

python
class Thing: pass t = Thing() print(bool(t)) # True, because no __bool__ or __len__

✅ Summary

You define…bool(obj) is…
__bool__Uses the returned Boolean value
__len__, no __bool__False if len(obj) == 0, True otherwise
NeitherAlways True

🧠 Tip: Define __bool__ if you want explicit control over an object’s truthiness.

Tags: Technology,Python,Interview Preparation,

No comments:

Post a Comment