3 ms·
> ie, instead of > for line in lines: print(line) > we are supposed to be using > while line := f.readline(): print(line) No, we’re not. Walrus, in loops, I
by dragonwriter 5y ago
> ie, instead of
> for line in lines: print(line)
> we are supposed to be using
> while line := f.readline(): print(line)
No, we’re not. Walrus, in loops, IME, is more for replacing this pattern:
while True:
myvar = get_it()
if not ok(myvar):
break
# code that uses myvar
with this pattern:
while ok(myvar := get-it()):
# code that uses myvar
- onphonenow 5y agoFalse. I have been harshly attacked here on HN for suggesting things like for line in lines - literally been called "stupid". I'm not the only one who looked at the recommended examples of the use case here and went, huh? https://news.ycombinator.com/item?id=17450890 https://news.ycombinator.com/item?id=17450890 Recommended new way: if any(len(longline := line) >= 100 for line in lines): print("Extremely long line:", longline) Old way: for line in lines: if len(line) >= 100: print("Extremely long line:", line) break I prefer the old way. These were examples in the PEP! In your example get_it() might be better as a generator or iterable. A lot of code looks great if you push that type of thing down a bit, and sometimes memory is helped as well. Then you iterate over it, for values in get_it. This keeps python very natural. You start to get a lot of weird line noise type code with := vs the old python style which while a bit longer was basically psudo-code.
- usrbinbash 5y agoI still don't see the need for things like the walrus-operator. All it does is increase line-noise, and for what? So we don't have to write 2 short lines, or save an indentation level somewhere? There is a good reason why assignments in Golang are not expressions, even though they are in C, and the language is otherwise deliberately close to the mindset of C; The added convenience makes the code much harder to read. Sure; char c; while((c = getch()) != EOF) { // do something } requires less lines than; char c; while(1) { c = getch(); if (c == EOF) break; // do something } but it's also easier to read, because each line carries less information. That's what people call "line noise". IMO, := is a step in the wrong direction, and sadly I see python take more and more of these, going from the deliberately simple and clear language to something that's becoming needlessly hard to read by piling on things it doesn't even need.