Skip to content

prefer-walrus-stream-loop

Collapse a compact producer assignment and immediate sentinel break into a named-expression loop.

Why

A named-expression loop can state a repeated producer call and its termination condition together.

Fix

For if not value: break, use while (value := read()):. For if value is None: break, preserve the sentinel with while (value := read()) is not None:.

Examples

Before — flagged Producer loop preserves a None sentinel
app/messages.py
while True:
message = receive()
if message is None:
break
consume(message)
After — preferred Named-expression loop keeps accepting falsy messages
app/messages.py
while (message := receive()) is not None:
consume(message)
Before — flagged Stream loop assigns and then breaks
app/stream.py
while True:
chunk = stream.read(8192)
if not chunk:
break
process(chunk)
After — preferred Stream loop binds in its condition
app/stream.py
while chunk := stream.read(8192):
process(chunk)