Search code examples
pythonpriority-queue

Python PriorityQueue gets only part of tuple


I'm having issues with priority queue in Python. I put in a tuple and when I iterate over it I get the tuple iterated over. What I want and expected to happen is the get() function would just return the whole tuple instead of just the first value of the first tuple.

Adding to queue:

await priority_queue.put((3, 'Value1', 'Value2'))

Iteration of queue:

for i in await priority_queue.get():
    print(i)

Result I get:

> 3
> 'Value1'
> 'Value2'

Result I want:

> (3, 'Value1', 'Value2')

According to the docs

The lowest valued entries are retrieved first (the lowest valued entry is the one returned by sorted(list(entries))[0]). A typical pattern for entries is a tuple in the form: (priority_number, data).

Which makes me think something is wrong, though I don't completely understand what is meant here besides that it gets sorted.


Solution

  • The issue was how I was thinking about queues. (Thanks to @deadshot)

    print(priority_queue.get())
    

    Works and there is no iteration if you just want the first object in queue.

    while not priority_queue.empty():
        print(await priority_queue.get())
    

    Is a good way to iterate over each object by itself. (Also allows for better looping elsewhere)