Python Glossary Русский

Python 3.4+Async programmingterm

asyncio.PriorityQueue

queue

An asynchronous priority queue: get() returns the smallest item. You usually put (priority, data) tuples.

Syntax

q = asyncio.PriorityQueue(); await q.put((priority, data)); priority, data = await q.get()

Items are compared as a whole: with equal priorities the tuples are compared by the second field, and dicts or unordered objects there raise TypeError at put() time. So you put (priority, counter, data), where the counter also keeps arrival order. A smaller number means higher priority; for 'bigger is more urgent' negate it.

Examples

import asyncio
async def main():
    q = asyncio.PriorityQueue()
    for prio, job in [(2, 'отчёт'), (1, 'авария'), (3, 'почта')]:
        await q.put((prio, job))
    await asyncio.sleep(0.01)
    while not q.empty():
        print(await q.get())  # → (1, 'авария') / (2, 'отчёт') / (3, 'почта')
asyncio.run(main())
import asyncio
async def main():
    q = asyncio.PriorityQueue()
    await q.put((1, {'id': 'a'}))
    try:
        await q.put((1, {'id': 'b'}))  # равный приоритет — сравнение словарей
    except TypeError as e:
        print(type(e).__name__)  # → TypeError
    await asyncio.sleep(0.01)
asyncio.run(main())

See also

Open in the full glossarydocs.python.orgReport an inaccuracy