overriding bool() for custom class [duplicate] overriding bool() for custom class [duplicate] python python

overriding bool() for custom class [duplicate]


Is this Python 2.x or Python 3.x? For Python 2.x you are looking to override __nonzero__ instead.

class test:    def __nonzero__(self):        return False


If you want to keep your code forward compatible with python3 you could do something like this

class test:    def __bool__(self):        return False    __nonzero__=__bool__


If your test class is list-like, define __len__ and bool(myInstanceOfTest) will return True if there are 1+ items (non-empty list) and False if there are 0 items (empty list). This worked for me.

class MinPriorityQueue(object):    def __init__(self, iterable):        self.priorityQueue = heapq.heapify(iterable)    def __len__(self):        return len(self.priorityQueue)>>> bool(MinPriorityQueue([])False>>> bool(MinPriorityQueue([1,3,2])True