3

I'm using a Python queue:

q = Queue.Queue()

I'm putting objects of a certain class into the aforementioned queue using q.put(item). However, before putting the item into the queue, I would like to check if it exists in the queue already. Is there a way to do this? [without taking out all of the objects of the queue and then pushing them all back in]

Additionally:

I don't know how I could actually see the variables I'm putting into the queue (when debugging). I'm using Pydev, and all I could see in the variables window is stuff like not_empty and not_full. How could I see what's in the queue during run time?

Cheshie
  • 2,777
  • 6
  • 32
  • 51

3 Answers3

18

You can treat 'q.queue' as a list.

if item in q.queue:
   print("already there!")
Rik Verbeek
  • 502
  • 3
  • 8
  • 2
    On python2.5 this causes `:argument of type 'instance' is not iterable` – Arnold Roa Jun 10 '16 at 21:41
  • 2
    Does this not invite a race condition, between checking and printing/processing data – T0m Jul 27 '17 at 22:51
  • 2
    Sorry - for Python 3.6 the same error occurs -> TypeError: argument of type 'Queue' is not iterable – cslotty Jul 24 '19 at 09:12
  • Note that `q` is an instance of the `queue.Queue` object, whereas `q.queue` is a `collections.deque` argument that allows iteration. – GinTonic May 27 '20 at 14:54
1

If you want you can provide such mechanism to a class of your own.

class UniqueQueue:

    def __init__(self):
        self.__item_pool = []

    def push(self, item):
        if item not in self.__item_pool:
            self.__item_pool.append(item)

    def pop(self):
        return self.__item_pool.pop()
Raydel Miranda
  • 13,825
  • 3
  • 38
  • 60
1

Are you sure you need queue.Queue? queue.Queue is a synchronised collection, and so offers more functionality than is needed in most cases.

You may want to look at using queue.deque or possibly using this recipe to create your own OrderedSet.

eg.

q = queue.deque()
q.appendleft(1)
q.appendleft(2)
q.appendleft(3)
assert 2 in q
assert q.pop() == 1

In python 2, the queue module is called Queue.

Dunes
  • 37,291
  • 7
  • 81
  • 97