Dunder __bool__¶
Used for built-in truth value testing and invoked by the builtin bool(...) method. This method
should return either False or True booleans respectively and if a dunder __bool__ is omitted from
a class, instances of such class will be checked based on a __len__. In the event that __len__ exists,
anything other than nonzero is considered True. If neither a __bool__ or __len__ are defined, instances
of such classes are determined to be True in a boolean context.`
Examples¶
User defined classes by default will return True when evaluated in a boolean context. This is because
neither __bool__ or __len__ are defined.
Default User Defined Objects | |
|---|---|
In order to override the boolean behaviour, implement __bool__ and return True|False accordingly.
Custom dunder bool | |
|---|---|
If __len__ is implemented and __bool_ is not, __len__ is used as a fallback, where non-zero values
are considered True.
Fallback to __len__ | |
|---|---|