3 ms·
You can use iterators in a while loop like your for example, making it look as clean as the for. I feel like this is a case of personal preference over actual
by grebc 10d ago
You can use iterators in a while loop like your for example, making it look as clean as the for.
I feel like this is a case of personal preference over actual issue.
- adastra22 9d agoIterative aren’t a thing in C, where that code smell notion comes from.
- grebc 9d agoWhat are you even talking about.
- theamk 9d agoyou mean like that? todo_iter = iter(todo) while True: try: value = next(todo_iter) except StopIteration: break process(value) or like that? todo_iter = iter(todo) # Note: assume "todo" does not contain None while value := next(todo_iter, None): process(value) I'd say neither of those are as clean as a simple for loop: for value in todo: process(value) and yes, that's the case of a personal preference, although I'd bet a lot of Python programmers will share that preference with me. That's what "code smell" means, after all - it's not a bug which is clearly incorrect, it's a code which is best avoided based on reviewer's personal experience.
- grebc 9d agoYour for loop is using an iterator of some kind. Just because it’s hidden in your language of choice doesn’t mean it’s not there. While/for can achieve the same thing, sometimes while is more practical as the steps to complete are unknown. But sure, stick your simple iterating a fixed collection as why it demonstrates while is a lesser language feature.
- theamk 8d agoI think your arguments would be much stronger with some actual code samples. Usually, when the same code can be written either as range-based "for" or as a "while", the "for" will look better and have fewer possibility of bugs. If you have examples otherwise, I'd like to see them. (Note I am specifically talking about range-based/iterator-based "for", not the C's variant. Nor am I talking the cases where the "for" is hard to use, like when the size might change at runtime)
- grebc 7d agoLet's leave it there mate. You're not the OP, you/me we're only guessing what he/she might've meant.