When Python needs to determine if an object is “truthy” or “falsy”
(for example in an if statement or bool(obj)), it follows a specific fallback order:
-
__bool__– Python first looks for a__bool__method on the object. If present, it calls that method and uses the boolean result directly. -
__len__– If__bool__is not implemented, Python next looks for a__len__method. If that exists, it calls__len__()and treats the object asTrueif the result is non-zero, andFalseif the result is 0. -
Default
True– If neither__bool__nor__len__is defined, the object is consideredTrueby default. (This applies to most user-defined class instances unless they explicitly define one of the two methods.)
Thus, the truth value is False
only if:
-
The object defines
__bool__and it returnsFalse, or -
The object does not define
__bool__but defines__len__and__len__()returns0.
Otherwise, it is True.
Example with a custom class
class AlwaysTrue: pass # no __bool__, no __len__ class EmptyContainer: def __len__(self): return 0 class NonEmptyContainer: def __len__(self): return 5 class ExplicitFalse: def __bool__(self): return False # Testing print(bool(AlwaysTrue())) # True (default) print(bool(EmptyContainer())) # False (__len__ returns 0) print(bool(NonEmptyContainer()))# True (__len__ returns 5) print(bool(ExplicitFalse())) # False (__bool__ returns False)
Why this order?
It allows built-in types like lists, strings, and dicts to be
“falsy” when empty without needing a special __bool__. They just
implement __len__:
bool([]) # False – list.__len__ returns 0 bool([1,2]) # True – list.__len__ returns 2
Objects that want to be unconditionally
True can leave both methods undefined. If you want to make an object
explicitly falsy, define __bool__ to return
False.
This mechanism is defined in Python’s Truth Value Testing rules.
All Questions From This Chapter « Previously Next »

No comments:
Post a Comment