How to unget a line when reading from a file/stream iterator/generator?

George Sakkis george.sakkis at gmail.com
Mon Apr 28 22:49:57 EDT 2008


On Apr 28, 10:10 pm, pyt... at bdurham.com wrote:
> George,
>
> > Is there an elegant way to unget a line when reading from a file/stream iterator/generator?
>
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502304
>
> That's exactly what I was looking for!
>
> For those following this thread, the above recipe creates a generic
> object that wraps any iterator with an 'unget' ("push") capability.
> Clean and elegant!
>
> Thank you,
> Malcolm

A small suggestion: since unget is expected to be called infrequently,
next should better be faster for the common case instead of penalizing
it with a try/except:

    def next(self):
        if not self.pushed_back:
            return self.it.next()
        else:
            return self.pushed_back.pop()

George



More information about the Python-list mailing list