Skip to content
Rezha Julio
Go back

Queue in Python - Part 3

1 min read

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.


Related Posts


Previous Post
JS & Dom - Tips & Tricks #1
Next Post
Queue in Python - Part 2