In Python, what operator to override for "if object:"? In Python, what operator to override for "if object:"? python python

In Python, what operator to override for "if object:"?


Define a method __bool__ (Python 3.x) or __nonzero__ (2.x). Or define both for portability, with one returning the result of the other.


Implement __nonzero__ for Python 2 and __bool__ for Python 3:

class AlwaysTrueObject:    def __bool__(self):        return True    __nonzero__ = __bool__


If you implement __len__ Python will do that for you under the assumption that a length of 0 means that the object has a boolean value of False and that it has a boolean value of True otherwise.

If it makes no sense to implement __len__, you can implement __nonzero__ (or __bool__ in 3.x (only the name has changed)) which is supposed to return either True or False depending on the boolean value of the object.