3 ms·
You are supposed to write for x in iter(f.readline, ""): Or if you don't know what readline will return you can wrap it in your own lambda: for x in
by Asooka 7y ago
You are supposed to write
for x in iter(f.readline, ""):
Or if you don't know what readline will return you can wrap it in your own lambda:
for x in iter(lambda:f.readline() or None, None):
There is a lot you can do with iter to write the kind of loops you want but it's not well known for some reason. It's a very basic part of the language people seem to overlook. Walrus does however let you write the slightly more useful
while predicate(x:=whatever()):
Which doesn't decompose easily into iter form.
- stefco_ 7y agoThis is a good solution! I don't directly use `iter` very often so I only remember it's simplicity part of the time. Sadly, this is not the idiom I see in most places. I will say, though, that I was not comfortable using iterators when I first learned python; walrus strikes me as easier to grok for a novice (one of the ostensible Python target demographics) than iter. I'll bet this is why this simple form is not idiomatic (though you're right, it should be).