On Fri, May 11, 2018 at 1:06 AM, Chris Angelico <ros...@gmail.com> wrote: > On Fri, May 11, 2018 at 4:54 PM, Ian Kelly <ian.g.ke...@gmail.com> wrote: >> On Thu, May 10, 2018 at 11:45 PM, Steven D'Aprano >> <steve+comp.lang.pyt...@pearwood.info> wrote: >>> To be honest, I'm having trouble thinking of a good use-case for "while >>> True", now that we have infinite iterators. Most cases of >>> >>> while True: >>> x = get_item() >>> if not x: break >>> process(x) >>> >>> are better written as: >>> >>> for x in iterator: >>> process(x) >> >> x = get_item() >> while True: >> x = process(x) > > More likely: > > x = get_item() > while x: > process(x) > x = get_item() > > which (a) repeats the call to get_item, (b) doesn't support the > 'continue' statement, and (c) hides crucial loop iteration information > at the BOTTOM of the loop. > > But to make this iterator, you need to separate the while loop's > header from its body. Compare: > > while x := get_item(): > process(x) > > > def get_items(): > while True: > x = get_item() > if not x: return > yield x > > for x in get_items(): > process(x) > > It hasn't actually gotten rid of the fib of the infinite loop; all > it's done is wrap it up in a function. Yes, that can be of value; but > adding another level of indirection doesn't solve a problem, it just > moves it around.
You can get rid of the while loop: for x in iter(get_item, None): process(x) The reason I suggested the function I did is because the x in that case can't reasonably be turned into an iterator because the logic depends on the loop body. You can't encapsulate the iteration logic without having side-effects in the iteration or duplicating code. -- https://mail.python.org/mailman/listinfo/python-list