How to overide "for line in file:"

Duncan Booth me at privacy.net
Mon Feb 23 11:25:10 EST 2004


Harry George <harry.g.george at boeing.com> wrote in 
news:xqxsmh2dyyn.fsf at cola2.ca.boeing.com:

> Slightly off topic, how do you "reset" or backup an iter?  Someone
> asked me a couple of days ago how to use yield and then backup if the
> yielded line failed to meet certain criteria.  Essentailly a
> lookahead(1) situation.

Python defines iterables as having a method '__iter__' which returns an 
iterator, and iterators as having methods 'next' to return the next value, 
and '__iter__' which returns the iterator itself.

That's it. What you see on the tin is what you get.

Of course, if you need a resettable iterator, or one that can backtrack, 
then there is no any reason why you can't program it for yourself, but this 
functionality isn't part of the definition of an iterator.

> 
> Historically, I've made a list, kept track of the line index, and
> decremented that when I needed to backup.  Does iter have something
> equiv?

You could almost certainly implement this kind of functionality once and 
then use it to wrap any iterators that might need to backtrack:

>>> class IterWithPushback:
        def __init__(self, it):
                self.__iter = iter(it)
                self.__next = []
        def __iter__(self):
                return self
        def next(self):
                if self.__next:
                        return self.__next.pop()
                return self.__iter.next()
        def pushback(self, value):
                self.__next.append(value)

>>> myIter = IterWithPushback(range(5))
>>> for i in myIter:
        if i==3:
                myIter.pushback('a')
                myIter.pushback('z')
        print i

        
0
1
2
3
z
a
4
>>> 

This has unbounded pushback, and because you have to say what you are 
pushing back it doesn't need to hold any unneeded values (at the point 
where you are pushing values back you probably know what values you just 
got so you can push them back it you want the same values, or push back 
something different if you prefer).



More information about the Python-list mailing list