Simulating C-style for loops in python

Posted by YGA on Stack Overflow See other posts from Stack Overflow or by YGA
Published on 2010-04-29T21:30:26Z Indexed on 2010/04/29 21:47 UTC
Read the original article Hit count: 255

Filed under:

(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?

© Stack Overflow or respective owner

Related posts about python