Predict the output
A bounded asyncio queue of size 2. What does this print?
import asyncio
async def main() -> None:
q: asyncio.Queue[int] = asyncio.Queue(maxsize=2)
q.put_nowait(1)
q.put_nowait(2)
try:
q.put_nowait(3)
except asyncio.QueueFull:
print("full: producer must wait")
print(q.qsize())
asyncio.run(main())Hint 1 of 1
What does maxsize do?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A full: producer must wait then 2
Correct. The third put is refused, so memory stays bounded.
A bounded queue makes producers feel when consumers are behind. put_nowait raises QueueFull instead of growing past maxsize, so the queue still holds just 2 items.
Why not the others?
- B
3. maxsize=2 refuses a third item. - C It blocks forever. put_nowait raises instead of waiting; await put() would wait.
- D
full: producer must waitthen3. The refused item isn't added.