Python Glossary Русский

all Python 3queueterm

queue.PriorityQueue

queues

A thread-safe priority queue: get() returns the smallest item, typically a tuple (priority, data).

Syntax

q = queue.PriorityQueue(maxsize=0); q.put((priority, data))

It is built on heapq, so a smaller number means higher priority. When priorities tie, tuples are compared by their second item, and if the data is not comparable (dicts, custom objects) you get TypeError. Fix it with a counter, (priority, count, data), or a dataclass(order=True) with field(compare=False) on the data.

Examples

import queue
q = queue.PriorityQueue()
q.put((2, 'low'))
q.put((1, 'high'))
print(q.get())  # → (1, 'high')
import queue
q = queue.PriorityQueue()
q.put((1, {'job': 'a'}))
try:
    q.put((1, {'job': 'b'}))
except TypeError as e:
    print(type(e).__name__)  # → TypeError

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy