Queue in Python - Part 3
Mon Dec 26, 2016 · 91 words

Prioritize your queue

A PriorityQueue is a type of queue imported from the module with the same name.

It uses sort order to decide what to retrieve from it first (your object must have a way of comparing its instances):

import queue

class Rezha(object):
    def __init__(self, priority):
       self.priority = priority
       
    def __lt__(self, other):
       return self.priority > other.priority

q = queue.PriorityQueue()
q.put(Rezha(11))
q.put(Rezha(55))
q.put(Rezha(100))
while not q.empty():
    print(q.get().priority)
# output is 100 / 55 / 11

Having defined the __lt__ method, our PriorityQueue knows now how to sort elements of type Rezha.


back · he thought · he could · so he did · main