Search code examples
pythonpython-3.xqueuepriority-queue

python3 priorityqueue size by priority?


is there a way to take the .size() of the priority queue ... for each priority level?

say i have an object, which i will put in a priority queue, with a priority based on the state of some_variable ...

q = PriorityQueue()

if some_variable:
    q.put((1, my_object))
else:
    q.put((2, my_object))

can i then find out, by asking for some kind of .qsize() method, such as a variant maybe of...

q.qsize() 

but instead of the total size of the queue, i'd like to know the size for each of the two separate 'groups'/priorities (qsize where priority==1, qsize where priority==2), in this case.

as opposed to just the total q.qsize()? hopefully that makes sense.


Solution

  • The simplest way I can see to do this would be

    from collections import Counter
    sizeByPriority = Counter(priority for priority, _elem in q.queue)
    

    but of course this requires iterating over the entire queue, which may be prohibitive in your situation, and probably isn't thread-safe.