PEP 572: Assorted fixes suggested by Rob Cliffe by gvanrossum · Pull Request #719 · python/peps

...
# A loop that can't be trivially rewritten using 2-arg iter()
while (value := read_next_item(file)) is not None:
# Do something with value

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ick - this example seems wholly contrived. How about keeping the original # A more explicit ... comment but changing the example to match it?

Before:
    for line in iter(somefile.readline, ""):
        process(line)
After:
    while line := somefile.readline():
        process(line)

Maybe that just especially appeals to me because I can never remember what 2-arg iter() does ☹️

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The problem with file based examples is that they typically collapse down to for line in somefile: ... in real code. It really is only in cases where native iteration support isn't available for some reason that you need to resort to the loop-and-a-half pattern instead.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Another real-world example involving files is:

while chunk := somefile.read(8192):
     process(chunk)

It doesn't belong to this paragraph though (I'm merely mentioning it)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@giampaolo, I think that would be an excellent example to replace the one here! The clumsy 2-arg iter way of spelling that is

for chunk in iter((lambda: somefile.read(8192)), ""):

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adding this now.