PYTHON
Implement a Priority Queue using `heapq`
Manage tasks or events by priority using Python's `heapq` module. Essential for scheduling and processing prioritized items in backend web services and task runners.
import heapq
class PriorityQueue:
def __init__(self):
self._queue = []
self._index = 0 # To break ties for items with the same priority
def push(self, item, priority):
# Items are stored as (priority, index, item)
# The index ensures that items with the same priority are retrieved in FIFO order
heapq.heappush(self._queue, (priority, self._index, item))
self._index += 1
def pop(self):
if not self._queue:
raise IndexError("pop from empty priority queue")
return heapq.heappop(self._queue)[2] # Return the actual item
def is_empty(self):
return not self._queue
def size(self):
return len(self._queue)
# Example Usage:
pq = PriorityQueue()
pq.push('Task C', 3) # Lower number means higher priority
pq.push('Task A', 1)
pq.push('Task B', 2)
pq.push('Task D', 3) # Same priority as C, but added later
print(f"Priority Queue Size: {pq.size()}")
print("Processing tasks by priority:")
while not pq.is_empty():
next_task = pq.pop()
print(f"Processing: {next_task}")
How it works: This snippet demonstrates implementing a priority queue using Python's `heapq` module. A priority queue is a data structure where each element has a 'priority', and elements with higher priority are served before elements with lower priority. The `heapq` module provides an efficient implementation of the heap queue algorithm (min-heap). Here, items are pushed as tuples `(priority, index, item)`, where `index` serves as a tie-breaker for items with identical priorities, ensuring stable ordering. This pattern is widely used in web development for task scheduling, managing background jobs, or processing events in a specific order in backend services.