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 toFalse
iflen(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