Python Forum

Full Version: Is there an iterable queue in python?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Python 3.7.1

I found queue class in the standard library. Unfortunately, in the help it's not written that it's iterable, but I need queue that provide iteration in back direction (without deleting elements from queue, to read items only).

How I can decide this question?
You could perhaps use a collections.deque instance
>>> from collections import deque
>>> d = deque(range(10))
>>> for item in reversed(d):
...     print(item)
... 
9
8
7
6
5
4
3
2
1
0
The class Queue is not subscriptable nor iterable.
A naive way to add iteration support to the Queue class, is done by inheritance and magic methods:

class IterQueue(queue.Queue):
    def __iter__(self):
        while True:
            yield self.get()
If you iterate over this object, the iteration never stops. Creating finite lists from this object was not my intention.

The deque object is also thread safe, so you can use it in threads, but it's a different implementation as a queue.

A queue blocks (default behavior) for example, if the queue is full (given maxsize).
A deque object does not block, if the maxsize has been reached. In this case the last or first element is dropped from the list.

In addition you can join a queue object. For each submitted element to the queue, you've to call queue.task_done().
Joining the queue blocks until all taks are marked as done. The deque object don't have this mechanism.

A deque object is not a drop-in-replacement for queue objects.
Gribouillis, thank you!