[Python-Dev] Priority queue (binary heap) python code

Gustavo Niemeyer niemeyer@conectiva.com
Tue, 25 Jun 2002 13:02:16 -0300

> it takes a whopping four lines of code, if you're a pragmatic
> programmer:

Indeed. Using a tuple directly was a nice idea! I was thinking about a
priority parameter (maybe I'm not that pragmatic? ;-), which is not hard
as well, but one will have to overload the put method to pass the
priority parameter.

import Queue, bisect

class PriorityQueue(Queue.Queue):
    def __init__(self, maxsize=0, defaultpriority=0):
        self.defaultpriority = defaultpriority
        Queue.Queue.__init__(self, maxsize)

    def put(self, item, block=1, **kw):
        if block:
        elif not self.fsema.acquire(0):
            raise Full
        was_empty = self._empty()
	# <- Priority could be handled here as well.
        self._put(item, **kw)
        if was_empty:
        if not self._full():

    def _put(self, item, **kw):
	# <- But here seems better
        priority = kw.get("priority", self.defaultpriority)
        bisect.insort(self.queue, (priority, item))

    def _get(self):
        return self.queue.pop(0)[1]

Gustavo Niemeyer

[ 2AAC 7928 0FBF 0299 5EB5  60E2 2253 B29A 6664 3A0C ]