Skip to content

Python · maintainability

prefer-walrus-stream-loop

python:prefer-walrus-stream-loop

Bind each stream value in the `while` condition instead of using an explicit break.

Code
SARJ077
Default
error
Fix
none
Languages
python

Why

A named-expression loop states the read, sentinel check, and iteration condition in one place.

Fix

Replace the leading assignment and immediate sentinel break with `while (value := read()):`.

Before / after

Executed by this rule’s unit tests.

Before

Stream loop assigns and then breaks

app/stream.py · focus
while True:
    chunk = stream.read(8192)
    if not chunk:
        break
    process(chunk)

After

Stream loop binds in its condition

app/stream.py · focus
while chunk := stream.read(8192):
    process(chunk)

Limits

  • Only `while True` loops beginning with a simple assignment and an immediate falsy or `None` break are analyzed.
  • Loops with an `else`, complex assignment targets, or additional work before the sentinel check are excluded.