According to Python's documentation on truth value testing:
Any object can be tested for truth value, for use in an if
or while
condition or as operand of the Boolean operations below.
By default, an object is considered true unless its class defines
either a __bool__()
method that returns False
or a __len__()
method
that returns zero, when called with the object.
In the code you reference, __nonzero__()
is the Python 2 equivalent of Python 3's __bool__()
.
So, an alternative to the __bool__()
method in your question could be something like:
class Lenny:
def __len__(self):
return 0 if self.value == '#' else len(self.children)
Note: None of this has anything much to do with the title of your question: "When can self == None". Equality (whether to None
or to anything else) is a different concept from truth value, and is defined by the __eq__()
method:
class Nonelike:
def __eq__(self, other):
return other == None