Overwriting / reassigning instance / garbage collection?

David C. Fox davidcfox at post.harvard.edu
Thu Oct 30 15:20:17 EST 2003


Ken Godee wrote:

> Werner Schiendl wrote:
> 
>>> q1 now has a new address, so I'm
>>> assuming the old q1 instance now has a
>>> reference count of zero and python will garbage collect it?????
>>>
>>
>> of course, the old one will eventually be garbage collected.
>>
>> The question is, what do you actually want to do?
>>
> 
> Actually, all I want to do is "clear" the queue.
> 
> I saw some other queue modules and they include
> a method to clear the queue.
> ie...
> 
> q1.clear()
> 
> but as far as I can tell the standard included Queue module
> that comes with python lacks this method.

A queue is a data structure with the restriction that elements are added 
to it on one end and removed on the other (also known as first-in 
first-out, because the first element added will be the first to be removed).

The Queue in the Queue module is not just a queue data structure - it is 
designed to be safely shared between multiple program threads, with only 
only one thread allowed to access it at one time.  The idea is to ensure 
that requests from 1 or more thread are handled in order, and none of 
them are lost.  Therefore, it usually doesn't make sense to clear the 
queue (deliberately losing all elements)

Those other queue modules you saw were probably implementing only the 
data structure, and not the multi-threaded aspects of Queue.Queue.

If you understand this, and *really* do want to discard all the elements 
from a Queue.Queue, you can just do:

try:
     while 1:
         q1.get(0)
except Queue.Empty:
     pass

However, you should be aware that any other parts of the program which 
have references to q1 can always add more elements to q1, so it won't 
necessarily stay empty.  Also, if you do have a multi-threaded 
application, and other threads are adding elements to the Queue faster 
than the code above can remove them, the code above might never finish.

David
> 
> 
> 





More information about the Python-list mailing list