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

MRAB python at mrabarnett.plus.com
Wed Jul 4 19:49:52 EDT 2018


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]


More information about the Python-Dev mailing list