pushback iterator

Matus matusu at gmail.com
Sun May 17 10:39:38 EDT 2009


Hallo pylist,

I searches web and python documentation for implementation of pushback
iterator but found none in stdlib.

problem:
========
when you parse a file, often you have to read a line from parsed file
before you can decide if you want that line it or not. if not, it would
be a nice feature to be able po push the line back into the iterator, so
nest time when you pull from iterator you get this 'unused' line.

solution:
=========
I found a nice and fast solution somewhere on the net:

---------------------------------------------------------------------
class Pushback_wrapper( object ):
	def __init__( self, it ):
		self.it = it
		self.pushed_back = [ ]
		self.nextfn = it.next
	
	def __iter__( self ):
		return self
	
	def __nonzero__( self ):
		if self.pushed_back:
			return True
		
		try:
			self.pushback( self.nextfn( ) )
		except StopIteration:
			return False
		else:
			return True

	def popfn( self ):
		lst = self.pushed_back
		res = lst.pop( )
		if not lst:
			self.nextfn = self.it.next
		return res
		
	def next( self ):
		return self.nextfn( )

	def pushback( self, item ):
		self.pushed_back.append( item )
		self.nextfn = self.popfn
---------------------------------------------------------------------

proposal:
=========
as this is (as I suppose) common problem, would it be possible to extend
the stdlib of python (ie itertools module) with a similar solution so
one do not have to reinvent the wheel every time pushback is needed?


thx, Matus



More information about the Python-list mailing list