How to check if object exists in queue before pushing new object
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
.
Cheshie
Updated on June 30, 2022Comments
-
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 likenot_empty
andnot_full
. How could I see what's in the queue during run time? -
Arnold Roa almost 8 yearsOn python2.5 this causes
<type 'exceptions.TypeError'>:argument of type 'instance' is not iterable
-
T0m almost 7 yearsDoes this not invite a race condition, between checking and printing/processing data
-
cslotty almost 5 yearsSorry - for Python 3.6 the same error occurs -> TypeError: argument of type 'Queue' is not iterable
-
GinTonic almost 4 yearsNote that
q
is an instance of thequeue.Queue
object, whereasq.queue
is acollections.deque
argument that allows iteration.