Python Glossary Русский

Python 3.4+Async programmingterm

asyncio.LifoQueue

queue

An asynchronous last-in, first-out queue: get() returns the most recently added item. The interface is the same as asyncio.Queue.

Syntax

q = asyncio.LifoQueue(maxsize=0); await q.put(x); x = await q.get()

It is essentially a stack with waiting: get() on an empty queue waits, and so does put() on a full one (when maxsize is set). For a stack inside one coroutine you need no queue — a list with append() and pop() will do; LifoQueue pays off when different tasks push and pop. It is not queue.LifoQueue from the queue module: that one is for threads and its get() blocks the whole event loop.

Examples

import asyncio
async def main():
    q = asyncio.LifoQueue()
    for x in (1, 2, 3):
        await q.put(x)
    await asyncio.sleep(0.01)
    print([q.get_nowait() for _ in range(3)])  # → [3, 2, 1]
asyncio.run(main())

See also

Open in the full glossarydocs.python.orgReport an inaccuracy