def PriorityQueue(initial_tasklist):
    'Retrieve tasks by priority.  Tasks can be removed or reprioritized.'
    from heapq import heappush, heappop

    pq = []                         # list of entries arranged in a heap
    entry_finder = {}               # mapping of tasks to entries
    REMOVED = object()              # placeholder for a removed task
    count = 0                       # unique sequence count

    def add(task, priority=0):
        'Add a new task or update the priority of an existing task'
        nonlocal count
        if task in entry_finder:
            remove(task)
        entry = [priority, count, task]
        entry_finder[task] = entry
        heappush(pq, entry)
        count += 1

    def remove(task):
        'Mark an existing task as REMOVED.  Raise KeyError if not found.'
        entry = entry_pop(task)
        entry[-1] = REMOVED

    def pop():
        'Remove and return the lowest priority task. Raise KeyError if empty.'
        while pq:
            priority, count, task = heappop(pq)
            if task is not REMOVED:
                del entry_finder[task]
                return task
        raise KeyError('pop from an empty priority queue')

    def __iter__():
        'Show task in order of priority'
        pq.sort()
        for priority, count, task in pq:
            if task is not REMOVED:
                yield task

    def __repr__():
        return 'PriorityQueue()'

    def __str__():
        return 'PriorityQueue with %d pending tasks' % __len__()

    # Delegate some of the work to the entry_finder dictionary
    __contains__ = entry_finder.__contains__
    __len__ = entry_finder.__len__
    entry_pop = entry_finder.pop

    # No separate method needed for initialization
    for task, priority in initial_tasklist:
        add(task, priority)

    return classify()
Retrieve tasks by priority.  Tasks can be removed or reprioritized.
recipes/Python/578091_Simple_tool_simulating_classes_using_closures/recipe-578091.py