1

Clear all items from the queue

I read the above answer

Im using python 2.7

import Queue
pq = Queue.PriorityQueue()
pq.clear()

I get the following error:

AttributeError: PriorityQueue instance has no attribute 'clear'

Is there way to easily empty priority queue instead of manually popping out all items? or would re-instantiating work (i.e. it wouldn't mess with join())?

Community
  • 1
  • 1
ealeon
  • 12,074
  • 24
  • 92
  • 173
  • The linked answer suggests to use `pg.queue.clear()`. –  Jul 25 '16 at 06:19
  • pq.queue.clear() AttributeError: 'list' object has no attribute 'clear' – ealeon Jul 25 '16 at 06:23
  • @Evert still error – ealeon Jul 25 '16 at 06:23
  • `.queue` is undocumented for `Queue()`, so I suspect it's a bit of a hack, and (obviously) can't be relied upon. See Kristof's answer. –  Jul 25 '16 at 06:27
  • 1
    Are you sure you need to be using the `Queue` module? It's not a general purpose data structure, but specifically for synchronized communication between threads. If you don't need the synchronization and just want a generic LIFO queue, use a `collections.deque`. For an unsynchronized priority queue, use a `list` and the functions in the `heapq` module. – Blckknght Jul 25 '16 at 06:34

1 Answers1

1

It's actually pq.queue.clear(). However, as mentioned in the answers to the question you referenced, this is not documented and potentially unsafe.

The cleanest way is described in this answer:

while not q.empty():
    try:
        q.get(False)
    except Empty:
        continue
    q.task_done()

Re-instantiating the queue would work too of course (the object would simple be removed from memory), as long as no other part of your code holds on to a reference to the old queue.

Community
  • 1
  • 1
DocZerø
  • 8,037
  • 11
  • 38
  • 66