[Python-Dev] Assignment expression and coding style: the while True case

Victor Stinner vstinner at redhat.com
Wed Jul 4 20:11:43 EDT 2018


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.

Victor

2018-07-05 1:49 GMT+02:00 MRAB <python at mrabarnett.plus.com>:
> On 2018-07-04 23:51, Victor Stinner wrote:
> [snip]
>>
>> (C)
>>
>> while True:
>>      chunk = self.raw.read()
>>      if chunk in empty_values:
>>          nodata_val = chunk
>>          break
>>      ...
>>
>> "nodata_val = chunk" cannot be put into the "chunk := self.raw.read()"
>> assignment expression combined with a test. At least, I don't see how.
>>
> If that's the only 'break' in the loop, then you know that 'chunk' will have
> an 'empty' value after the loop, so you can change it to:
>
> while True:
>     chunk = self.raw.read()
>     if chunk in empty_values:
>         break
>     ...
> nodata_val = chunk
>
> which then leads to:
>
> while (chunk := self.raw.read()) not in empty_values:
>     ...
> nodata_val = chunk
>
> [snip]
> _______________________________________________
> Python-Dev mailing list
> Python-Dev at python.org
> https://mail.python.org/mailman/listinfo/python-dev
> Unsubscribe:
> https://mail.python.org/mailman/options/python-dev/vstinner%40redhat.com


More information about the Python-Dev mailing list