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:
-
If
__bool__is not defined, Python checks for__len__. -
If
__len__is defined:-
if obj:will evaluate toFalseiflen(obj) == 0. -
Otherwise, it evaluates to
True.
-
-
If neither
__bool__nor__len__is defined, the object is considered truthy by default (i.e.,True).
π Example Without __bool__:
π§± Example With Neither:
✅ Summary
| You define… | bool(obj) is… |
|---|---|
__bool__ | Uses the returned Boolean value |
__len__, no __bool__ | False if len(obj) == 0, True otherwise |
| Neither | Always True |
π§ Tip: Define
__bool__if you want explicit control over an object’s truthiness.

No comments:
Post a Comment