<div dir="ltr"><div><div><div>Following the discussion of the new "async" keyword, I think it would be useful to provide a generic way to alter the behavior of loops.  My idea is to allow a user to take control over the operation of a "for" or "while" loop.  <br><br></div>The basic idea is similar to context managers, where an object implementing certain magic methods, probably "__for__" and "__while__", could be placed in front of a "for" or "while" statement, respectively.  This class would then be put in charge of carrying out the loop.  Due to the similarity to context managers, I am tentatively calling this a "loop manager".<br><br></div>What originally prompted this idea was parallelization.  For example the "multiprocessing.Pool" class could act as a "for" loop manager, allowing you to do something like this:<br><br></div><div> >>> from multiprocessing import Pool<br> >>><br></div><div> >>> Pool() for x in range(20):<br></div><div> ...    do_something<br> ...<br> >>><br><br></div><div>The body of the "for" loop would then be run in parallel.<br><br></div><div>However, there are other uses as well.  For example, Python has no "do...while" structure, because nobody has come up with a clean way to do it (and probably nobody ever will).  However, under this proposal it would be possible for a third-party package to implement a "while" loop manager that can provide this functionality:<br><br></div><div> >>> from blah import do<br> >>><br></div><div> >>> x = 10<br></div><div> >>> do while x < 20:<br></div><div> ... x += 1<br> ...<br> >>><br><br></div><div>The "do" class would just defer running the conditional until after executing the body of the "while" loop once.<br><br></div><div>Another possible use-case would be to alter how the loop interacts with the surrounding namespace.  It would be possible to limit the loop so only particular variables become part of the local namespace after the loop is finished, or just prevent the index from being preserved after a "for" loop is finished.<br><br></div><div>I think, like context managers, this would provide a great deal of flexibility to the language and allow a lot of useful behaviors.  Of course the syntax and details are just strawmen examples at this point, there may be much better syntaxes.  But I think the basic idea of being able to control a loop in a manner like this is important.<br></div></div>