import heapq import itertools # A unique sequence count for tie-breaking, ensuring consistent ordering for same-priority items # and that items added earlier with same priority are retrieved earlier. count = itertools.count() # Our priority queue pq = [] # Function to add a task def add_task(priority, task): 'Add a new task or update the priority of an existing task' entry = [priority, next(count), task] # priority, entry_id, task heapq.heappush(pq, entry) # Function to get the next task def get_next_task(): 'Remove and return the lowest priority task' if pq: priority, id, task = heapq.heappop(pq) return task return None # Example Usage add_task(5, 'Low priority background job') add_task(1, 'High priority user request') add_task(3, 'Medium priority cache update') add_task(1, 'Another high priority user request') # Same priority, different entry_id print(f"Next task: {get_next_task()}") # Should be 'High priority user request' print(f"Next task: {get_next_task()}") # Should be 'Another high priority user request' print(f"Next task: {get_next_task()}") # Should be 'Medium priority cache update' print(f"Next task: {get_next_task()}") # Should be 'Low priority background job' print(f"Next task: {get_next_task()}") # Should be None (queue is empty)