[Python-Dev] Assignment expression and coding style: the while True case
MRAB
python at mrabarnett.plus.com
Wed Jul 4 21:33:44 EDT 2018
On 2018-07-05 01:11, Victor Stinner wrote:
> The code comes from Lib/_pyio.py. Simplified code:
> ---
> nodata_val = b""
> ...
> if n is None or n == -1:
> ...
> current_size = 0
> while True:
> chunk = self.raw.read()
> if chunk in empty_values:
> nodata_val = chunk
> break
> current_size += len(chunk)
> chunks.append(chunk)
> return b"".join(chunks) or nodata_val
>
> ...
> while avail < n:
> chunk = self.raw.read(wanted)
> if chunk in empty_values:
> nodata_val = chunk
> break
> avail += len(chunk)
> chunks.append(chunk)
>
> ...
> return out[:n] if out else nodata_val
> ---
>
> It seems like "nodata_val = " assignment can be moved out of the first
> loop, but cannot be moved for the second loop (since the second loop
> has no iteration if "avail >= n").
>
> Yeah, maybe for this specific file, assignment expressions could be
> used for the (C) case and would be worth it.
In this case, the second loop might be better left as-is because there
are 2 conditions for leaving the loop. Stylistically, it might be
starting to hurt readability with something like:
while avail < n or (chunk := self.raw.read(wanted)) not in empty_values:
[snip]
More information about the Python-Dev
mailing list