Question

I want to know if there is any way to check if an object is already in the pririty queue by their __hash__ and __ep__. I have to code in Python 2.7 . Here is an example Code which should print "foo":

import Queue

class Job(object):
    def __init__(self, fpriority, spriority, iata , hops, cost):
        self.fpriority = fpriority
        self.spriority = spriority
        self.iata = iata
        self.hops = hops
        self.cost = cost

    def __eq__(self,other):
        return (self.fpriority == other.fpriority and self.spriority == other.spriority and self.iata == other.iata)

    def __hash__(self):
        return hash((self.fpriority , self.spriority , self.iata))    

    def __cmp__(self, other):
        if self.fpriority > other.fpriority:
            return 1
        elif self.fpriority < other.fpriority:
            return -1
        else:
            if self.spriority > other.spriority:
                return 1
            elif self.spriority < other.spriority:
                return -1
            else:
                return 0

q = Queue.PriorityQueue()
q.put(Job(153153, 0,  'b', 1 , 1))
q.put(Job(145, 2,  'a', 1 , 1))
k = Job(145, 2,  'a', 1 , 1)

for l in q:
    if k == l:
        print "foo"
Was it helpful?

Solution

This is hacky and is not guaranteed to work in different implementations/versions of python.

The contents of the PriorityQueue is kept in its queue member, which is a plain list. Therefor, you can test for item existence using in. Since queues are typically used in a multi-threading/processing environment, you probably also want to lock (using its mutex member):

def is_in_queue(x, q):
   with q.mutex:
      return x in q.queue

This is a linear lookup in a list, using the == operator on the items. __hash__ is not used.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top