[Python-ideas] "continue with" for dynamic iterable injection

Cameron Simpson cs at zip.com.au
Thu Sep 25 03:13:40 CEST 2014


On 24Sep2014 23:09, Cathal Garvey <cathalgarvey at cathalgarvey.me> wrote:
>The conversation began with me complaining that I'd like a third mode of
>explicit flow control in Python for-loops; the ability to repeat a loop
>iteration in whole. The reason for this was that I was parsing data
>where a datapoint indicated the end of a preceding sub-group, so the
>datapoint was both a data structure indicator *and* data in its own
>right. So I'd like to have iterated over the line once, branching into
>the flow control management part of an if/else, and then again to branch
>into the data management part of the same if/else.

Sounds a bit like Perl's "redo" statement. Example (pretending Python syntax):

   for x in iterable_thing:
     if special_circumstance_here:
       x = 9
       redo

Perl lets you redo to a special label, too (good practice actually - all sorts 
of horrible subtle bugs can come in with bare redos).

In Python you'd be better off writing a special iterator with "push back". You 
used to find this kind of thing on I/O streams and parsers.

Example use:

   I2 = PushableIter(iterable_thing)
   for x in I2:
     if special_circumstance_here:
       I2.push_back(9)
     else:
       rest of loop ...

Then "PushableIter" is a special iterator that keeps a "pushed back" variable 
or stack. Simple untested example:

   class PushableIter:

     def __init__(self, iterable):
       self.pushed = []
       self.iterator = iter(iterable)

     def __next__(self):
       if self.pushed:
         return self.pushed.pop()
       return next(self.iterator)

     def push_back(self, value):
       self.pushed.append(value)

Should slot into the above example directly. Keep it around in your convenience 
library.

This doesn't require modifying the language to insert is special purpose and 
error prone contruct. Instead, you're just making a spceial iterator. Which 
also leaves you free to make _other_ special iterators for other needs.

Cheers,
Cameron Simpson <cs at zip.com.au>

[...] post-block actions should be allowed everywhere, not just on
subroutines. The ALWAYS keyword was agreed upon as a good way of doing
this, although POST was also suggested. This lead to the semi-inevitable
rehash of the try- catch exception handling debate. According to John
Porter, "There is no try, there is only do. :-)"
- from the perl6 development discussion


More information about the Python-ideas mailing list