[ACCEPTED]-how to deepcopy a queue in python-queue

Accepted answer
Score: 10

The queue module in Python is used for synchronizing 10 shared data between threads. It is not intended 9 as a data structure and it doesn't support 8 copying (not even shallow copy).

(It is possible 7 to construct many deepcopy's of a Queue 6 by .get and .put, but the original Queue will be 5 destroyed.)

If you want to have a queue (or 4 stack) as a data structure, use a collections.deque. If you want 3 a priority queue, use the heapq module. The deque supports 2 deepcopy. heapq is backed by a list, so 1 deepcopy is also supported.

Score: 0

Don't know your exact need but it could 4 be that you would be interested of this 3 code I posted in DaniWeb discussion about 2 priority queue. The list is easy to save 1 copy by slicing etc.

#Python 2.6.5
from random import randint
class Priority:
   def __init__(self,prioritylevels=5):
      """The constructor builds list for priority queue which would be used later
      """
      self.prioritylevels = prioritylevels
      self.pq = [[] for priority in range(self.prioritylevels)] # prioritylevels

   def add_to_queue(self, data, priority=None):
       """Add every received in data and use priority parameter or
         its priority key to get its priority value (1 == highest) in the global queue
       """
       if priority is None: priority = data['priority']-1
       else: priority -= 1

       if 0 <= priority < self.prioritylevels:
             self.pq[priority].append(data)
       else: raise ValueError,"Priority level out of bounds: %s" % priority

   def get(self):
       """ get lowest priority values first from queue """
       for priorityevents in self.pq:
            while priorityevents:
                yield priorityevents.pop(0) ## use list as queue to keep insertion order (remove from front)               
   def num_items(self):
      return sum(len(q) for q in self.pq)


if __name__ == '__main__':

   myqueue = Priority(8)
   for i in range(100000):
      item=randint(0,234234)
      if not i % 10000: print i,
      priority=(item & 0b111) +1 ## lets three lowest bits decide which priority we give
      myqueue.add_to_queue(('Number',item),priority=priority)

   print "\n%i items in queues" % myqueue.num_items()
   print "Items by priorities"
   print '\n'.join("%i: %i" % (priority+1,len(q)) for priority, q in enumerate(myqueue.pq))
   print "\nGetting items out of queue in priority order:"
   priority=0
   for description,i in myqueue.get():
       assert (i & 0b111 >= priority), '** Bug ***' ## validity test priority must be same or lower for items
       priority = i & 0b111 
   # empty after get
   print "Finished"
   print "%i items in queue" % myqueue.num_items()
Score: 0

You can copy members of one queue to another 1 with a simple code fragment as follows

# delcare queues 
q1 = queue.Queue()
q2 = queue.Queue()

# perform a deep copy ( copy all elemts from q2 to q1 ) 
while not q2.empty():
         q1.put(q2.get())
         q2.task_done()

More Related questions