(even the title of this is going to cause flames, I realize)
Python made the deliberate design choice to have the for loop use explicit iterables, with the benefit of considerably simplified code in most cases.
However, sometimes it is quite a pain to construct an iterable if your test case and update function are complicated, and so I find myself writing the following while loops:
val = START_VAL
while <awkward/complicated test case>:
# do stuff
...
val = <awkward/complicated update>
The problem with this is that the update is at the bottom of the while block, meaning that if I want to have a continue embedded somewhere in it I have to:
use duplicate code for the complicated/awkard update, AND
run the risk of forgetting it and having my code infinite loop
I could go the route of hand-rolling a complicated iterator:
def complicated_iterator(val):
while <awkward/complicated test case>:
yeild val
val = <awkward/complicated update>
for val in complicated_iterator(start_val):
if <random check>:
continue # no issues here
# do stuff
This strikes me as waaaaay too verbose and complicated. Do folks in stack overflow have a simpler suggestion?
Response to comments:
@Glenn Maynard: Yes, I dismissed the answer. It's bad to write five lines if there is a way to do it in one... especially in a case that comes up all the time (looping being a common feature of Turing-complete programs).
For the folks looking for a concrete example: let's say I'm working with a custom date library. My question would then be, how would you express this in python:
for (date = start; date < end; date = calendar.next_quarter_end(date)):
if another_calendar.is_holiday(date):
continue
# ... do stuff...