Nested iteration?

Peter Otten __peter__ at web.de
Tue Apr 23 12:15:42 EDT 2013


Roy Smith wrote:

> In reviewing somebody else's code today, I found the following
> construct (eliding some details):
> 
>     f = open(filename)
>     for line in f:
>         if re.search(pattern1, line):
>             outer_line = f.next()
>             for inner_line in f:
> if re.search(pattern2, inner_line):
>                     inner_line = f.next()
> 
> Somewhat to my surprise, the code worked.  I didn't know it was legal
> to do nested iterations over the same iterable (not to mention mixing
> calls to next() with for-loops).  Is this guaranteed to work in all
> situations?

That depends on what you mean by "all". A well-behaved iterator like 
Python's file object allows mixing of for loops and next(...) calls, but 
stupid people who deserve to burn in hell sometimes do

class MyIterable:
    def __iter__(self):
         reset_internal_counter()
         return self


with the consequence that every for loop implicitly resets the iterator's 
state.




More information about the Python-list mailing list