ungetch in Python

anton muhin antonmuhin at rambler.ru
Wed Dec 24 19:56:54 CET 2003


Scott Fenton wrote:

> Hello and merry chrismas/new years/<insert winter holiday> everyone,
> 
> I'm writing a small parser for a minilanguage in Python,
> and I was wondering --- is there any equiv. of C's ungetch
> or Scheme's peek-char in python? That is, is there a way to
> look at a character without taking it off of the input stream
> or is there a way to put it back on the input stream afterwards?
> I googled around and didn't come up with anything that didn't
> involve curses, which I don't want to use. Any help?
> 
> TIA
> -Scott

Merry christmas & Happy New Year!

First of all I'd rather suggest to use one of parsers for Python---there 
are plenty of them and they are really nice.

To your question: I don't remember this kind of function is Standard 
Lib, but chances are it is there. But still you can emulate it with your 
own iterator class.

Here comes an example:

class UngetIter(object):
     def __init__(self, it):
         self.it_ = iter(it)
         self.hasUnget_ = False
         self.last_ = None

     def __iter__(self):
         return self

     def next(self):
         if self.hasUnget_:
             self.hasUnget_ = False
             return self.last_

         return self.it_.next()

     def unget(self, o):
	assert not self.hasUnget_, 'Only one unget allowed!'
         self.hasUnget_ = True
         self.last_ = o

i = UngetIter('abc')
for n, e in enumerate(i):
     if n % 2 == 1:
         print 'unget', e
         i.unget(e)
     else:
         print e

Warning: almost not tested.

If you want to unget more than one char, you can just use a list of 
objects to unget.

regards,
anton.




More information about the Python-list mailing list