liveBook · Manning

Queue.put_nowait

As explained in Python Concurrency with asyncio

queue.put_nowait is a nonblocking queue method that immediately inserts an item or raises a full-queue exception.

queue.put_nowait is the nonblocking way to add an item to an asyncio queue. It returns immediately when space is available; when a bounded queue is full, it fails instead of waiting. section 12.1 section 12.1.1

Use it when the caller should not pause for capacity to become available. In a web endpoint, a full queue can therefore produce an error asking the caller to try again later, while await queue.put(...) waits until the item can be queued. section 12.1 section 12.1.1

A full bounded queue

queue = Queue(maxsize=1) queue.put_nowait(1) queue.put_nowait(2) The first insertion fits. The second insertion attempts to add an item while the queue is full and raises a full-queue exception rather than blocking. section 12.1

Fast order submission

An order route can choose queue.put_nowait when it needs fail-fast behavior: enqueue the order if capacity exists, or return an error so the caller can try again later. Using await order_queue.put(...) instead favors ensuring that every order reaches the queue, even if the request takes longer. section 12.1.1

import asyncio
from asyncio import Queue
 
 
async def main():
    queue = Queue(maxsize=1)
 
    queue.put_nowait(1)
    queue.put_nowait(2)
 
asyncio.run(main())

Shows the minimal bounded-queue insertion case, including two consecutive put_nowait calls against a queue with maxsize=1. section 12.1

How Python Concurrency with asyncio covers it

How deep it goes
Defines immediate insertion, contrasts it with coroutine put, and demonstrates bounded-queue failure without descending into implementation internals.
Examples
Demonstrates a maxsize-one queue and contrasts fail-fast order submission with waiting insertion in a web application.
What you can do after
Apply it to bounded queues when an application must return promptly instead of waiting for space.
How it connects
Connects asyncio queues, bounded queues, coroutine methods, queue fullness, and web request handling.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Concurrency with asyncio. The section links point to the parts of the book it draws on.