![]() |
Is there an iterable queue in python? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Is there an iterable queue in python? (/thread-14540.html) |
Is there an iterable queue in python? - AlekseyPython - Dec-05-2018 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? RE: Is there an iterable queue in python? - Gribouillis - Dec-05-2018 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 RE: Is there an iterable queue in python? - DeaD_EyE - Dec-05-2018 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. RE: Is there an iterable queue in python? - AlekseyPython - Dec-05-2018 Gribouillis, thank you! |