Search code examples
pythonlistobjectheappriority-queue

Issue using heapq in python for a priority list


I can't understand why my below code raise an error.

I'm trying to build a priority list based on heapq module of Python. The only difference with a basic example of the module is that want to use it with custom objects in it it, instead of simple (int,int) or (int,str) tuples.

import heapq

class MyObject():

 def __init__(self,a=0,name='toto'):

     self.a = a
     self.name = name

if __name__ == '__main__':

 priority_list = []
 heapq.heappush(priority_list,(1,MyObject()))
 heapq.heappush(priority_list,(1,MyObject()))

This is the error I have:

heapq.heappush(priority_list,(1,MyObject()))

TypeError: '<' not supported between instances of 'MyObject' and 'MyObject'

The error is not raised if I use a different key to insert in the heap, but isn't heapq supposed to deal with same keys? I don't understand very well this behaviour.

Thanks a lot


Solution

  • The operator < is not defined for your class. That way heapq can't define priority.

    ob1 = MyObject()
    ob1 < ob1
    

    raises

    TypeError: unorderable types: MyObject() < MyObject()
    

    You must then define the logical operators. See this for more info.

    class MyObject():
        def __init__(self,a=0,name='toto'):
            self.a = a
            self.name = name
    
        def __lt__(ob1, ob2):
            return ob1.a < ob2.a
    
    ob1 = MyObject()
    ob1 < ob1 # returns False