Search code examples
pythonnonetypetruthiness

When can self == None


I am looking at a snippet if not self: in an answer to another question which implements __nonzero__().

This gets me wondering: apart from __nonzero__() returning False or the trivial local assignment self = None, are there other situations, in which the conditional if not self is true?


Solution

  • 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