tags:

views:

70

answers:

2

Hi How to deepcopy a Queue in python? Thanks

A: 

Don't know your exact need but it could be that you would be interested of this code I posted in DaniWeb discussion about priority queue. The list is easy to save 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()
Tony Veijalainen
+4  A: 

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

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

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

KennyTM