[Python-ideas] Loop manager syntax

Todd toddrjen at gmail.com
Tue Jul 28 15:28:17 CEST 2015


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.

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".

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:

 >>> from multiprocessing import Pool
 >>>
 >>> Pool() for x in range(20):
 ...    do_something
 ...
 >>>

The body of the "for" loop would then be run in parallel.

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:

 >>> from blah import do
 >>>
 >>> x = 10
 >>> do while x < 20:
 ... x += 1
 ...
 >>>

The "do" class would just defer running the conditional until after
executing the body of the "while" loop once.

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.

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.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20150728/0a3ac8a9/attachment.html>


More information about the Python-ideas mailing list