PYTHON

Manage Prioritized Tasks with a Heap-based Priority Queue

Implement a Python priority queue using `heapq` to efficiently manage tasks or items based on their priority, crucial for scheduling background jobs, processing queues, or event handling.

import heapq

class PriorityQueue:
    def __init__(self):
        self._queue = []
        self._index = 0 # Used to ensure stable ordering for items with same priority

    def push(self, item, priority):
        # priority is negative to make it a min-heap (lower number = higher priority)
        # _index is used to break ties if priorities are equal (FIFO for same priority)
        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")
        # Retrieve item with highest priority (lowest negative priority value)
        priority, _, item = heapq.heappop(self._queue)
        return item

    def is_empty(self):
        return len(self._queue) == 0

    def size(self):
        return len(self._queue)

# Example Usage: Task Scheduler
task_queue = PriorityQueue()

print("Adding tasks...")
task_queue.push("Send welcome email", 3) # Low priority
task_queue.push("Process critical payment", 1) # High priority
task_queue.push("Update user profile", 2) # Medium priority
task_queue.push("Generate daily report", 3) # Another low priority task

print("
Processing tasks by priority:")
while not task_queue.is_empty():
    next_task = task_queue.pop()
    print(f"Processing: {next_task}")

# Expected Output:
# Adding tasks...
# 
# Processing tasks by priority:
# Processing: Process critical payment
# Processing: Update user profile
# Processing: Send welcome email
# Processing: Generate daily report
How it works: The `heapq` module in Python implements the heap queue algorithm, also known as the priority queue algorithm. This snippet wraps `heapq` to create a `PriorityQueue` class, allowing items to be added with an associated priority. Tasks with higher priority (lower numerical value in this implementation) are always processed first. A unique index is included in the stored tuple to ensure stable ordering (FIFO) for items sharing the same priority. This pattern is invaluable for web applications for managing background jobs, message queues, event processing, or any scenario where tasks need to be handled based on urgency.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs