How to unget a line when reading from a file/stream iterator/generator?
duncan.booth at invalid.invalid
Tue Apr 29 11:23:33 CEST 2008
George Sakkis <george.sakkis at gmail.com> wrote:
> On Apr 28, 10:10 pm, pyt... at bdurham.com wrote:
>> > Is there an elegant way to unget a line when reading from a
>> > file/stream
>> 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,
> 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()
> return self.pushed_back.pop()
If speed is an issue then it may be better to avoid the test altogether:
def __init__(self, it):
self.it = it
self.pushed_back = 
self.nextfn = it.next
lst = self.pushed_back
res = lst.pop()
if not lst:
self.nextfn = self.it.next
def pushback(self, item):
self.nextfn = self.popfn
More information about the Python-list