Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Python assignment expressions: capture a checked value once

Last updated: 30 Sept 20264 min read
tutorial
BeginnerBy AITrove Editorial

An assignment expression binds a name while returning that value to the surrounding expression.

Download Python source kit

Operation contract

The import reader returns one bounded line at a time. The loop captures each read, stops at the empty-string EOF sentinel and rejects an oversized line before publication. That differs from writing while (line := stream.readline()), which would also stop on an empty string but gives no size policy. The fixture counts only accepted, newline-stripped receipt IDs and shows that the reader was called once per record plus once for EOF.

Failure and ownership boundary

This syntax does not make a read atomic with a later write. A failed record should not publish earlier partial state unless the application declares that policy. Parentheses matter in conditions, and a captured mutable object may change later. Python CSV ingestion: cap bytes, rows and fields before publication, Python iterators: exhaustion and repeatable collection ownership and Python file project: stage a report before replacing the visible file extend the same input path.

Working program

python
from io import StringIO

def read_ids(stream):
    accepted = []
    reads = 0
    while (line := stream.readline(16)) != "":
        reads += 1
        if len(line) > 8 or not line.endswith("\n"):
            raise ValueError("bounded complete line")
        identifier = line[:-1]
        if len(identifier) != 3 or identifier[0] != "R" or any(char not in "0123456789" for char in identifier[1:]):
            raise ValueError("receipt identifier")
        accepted.append(identifier)
    return accepted, reads + 1

print(read_ids(StringIO("R41\nR42\n")))
try:
    read_ids(StringIO("R41\nBAD\n"))
except ValueError:
    print("invalid line rejected")

Output

Output
(['R41', 'R42'], 3)
invalid line rejected

Costs and limits

Reading n lines uses O(total bytes) time and O(n) output references plus text. The per-read cap prevents one returned chunk from exceeding sixteen characters but does not cap total records; add a record count for a public ingestion boundary.

Common Mistakes

  • A captured read value is not a transaction with later publication.
  • An empty-string EOF sentinel differs from a valid blank line.

Connected lessons

Python CSV ingestion: cap bytes, rows and fields before publication, Python iterators: exhaustion and repeatable collection ownership, Python file project: stage a report before replacing the visible file.

python
assignment-expression
Storage details