CKTIS / Python
asyncio.Queue
Provides first-in, first-out handoff between asynchronous producers and consumers.
Version: Python 3.14; repository image, production runtime not attested
Syntax
asyncio.Queue(maxsize=0)Provides first-in, first-out handoff between asynchronous producers and consumers.
A bounded queue rejects an immediate insertion when full. Mark retrieved items done so a join can finish.
A FIFO queue passes items between tasks. maxsize<=0 is unlimited. await put waits for space and await get for data; immediate operations can raise QueueFull or QueueEmpty. In the sample a full one-slot queue rejects 9, yields 8 and then task_done permits join to finish. Since 3.13 normal shutdown forbids new puts and lets existing items drain. join waits for the unfinished-work count to reach zero, and an extra task_done raises ValueError. shutdown(immediate=True) can discard unprocessed items. Apply a timeout via asyncio.wait_for; the queue is not thread-safe.
import asyncio
async def main():
q = asyncio.Queue(maxsize=1)
await q.put(7)
try:
q.put_nowait(8)
except asyncio.QueueFull:
pass
q.shutdown()
assert await q.get() == 7
q.task_done()
await q.join()
try:
await q.get()
except asyncio.QueueShutDown:
pass
else:
raise AssertionError
asyncio.run(main())
import asyncio
async def main():
q = asyncio.Queue()
await q.put(1)
q.shutdown(immediate=True)
await asyncio.wait_for(q.join(), 1)
assert q.empty()
try:
q.task_done()
except ValueError:
pass
else:
raise AssertionError
asyncio.run(main())
Examples
import asyncio
async def main():
queue = asyncio.Queue(maxsize=1)
await queue.put(8)
try:
queue.put_nowait(9)
except asyncio.QueueFull:
print(queue.full())
print(await queue.get())
queue.task_done()
await queue.join()
asyncio.run(main())
Result
True 8
A FIFO queue passes items between tasks. maxsize<=0 is unlimited. await put waits for space and await get for data; immediate operations can raise QueueFull or QueueEmpty. In the sample a full one-slot queue rejects 9, yields 8 and then task_done permits join to finish. Since 3.13 normal shutdown forbids new puts and lets existing items drain. join waits for the unfinished-work count to reach zero, and an extra task_done raises ValueError. shutdown(immediate=True) can discard unprocessed items. Apply a timeout via asyncio.wait_for; the queue is not thread-safe.