How to check if object exists in queue before pushing new object

13,977

Solution 1

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

if item in q.queue:
   print("already there!")

Solution 2

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()

Solution 3

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.

Share:
13,977
Cheshie
Author by

Cheshie

Updated on June 30, 2022

Comments

  • Cheshie
    Cheshie almost 2 years

    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?

  • Arnold Roa
    Arnold Roa almost 8 years
    On python2.5 this causes <type 'exceptions.TypeError'>:argument of type 'instance' is not iterable
  • T0m
    T0m almost 7 years
    Does this not invite a race condition, between checking and printing/processing data
  • cslotty
    cslotty almost 5 years
    Sorry - for Python 3.6 the same error occurs -> TypeError: argument of type 'Queue' is not iterable
  • GinTonic
    GinTonic almost 4 years
    Note that q is an instance of the queue.Queue object, whereas q.queue is a collections.deque argument that allows iteration.