Does Python support a peek like method for its file objects?

Scott David Daniels scott.daniels at acm.org
Sun Feb 5 11:16:36 EST 2006


Avi Kak wrote:
>   Does Python support a peek like method for its file objects?

A short answer is, "No, it does not."  Peek was (I believe) put into
Pascal to simplify certain problems; language processing , for example,
is drastically simplified by 1-character look-ahead.  Pascal was
designed as a teaching language, and it provided primitives to ease
the work students did, rather than reflect the realities of an
underlying I/O system.  Building usable Pascal runtimes was a pain in
the posterior for precisely this reason.

Often you can build simple code to accomplish your task without
implementing a full peek.  Peek affects: read, tell, relative seeks,
end-of-file processing, and waits for user interaction.  usually you
need nearly none of this.  Maybe all you need is a layer around a
reader with a "pushback" function.

class ReaderWithPushback(object):
         def __init__(self, somefile):
             self._read = somefile.read
             self.held = ''
             self.sawEOF = False

         def read(self, length):
             assert length > 0
             while len(self.held) < length and not self.sawEOF:
                 chunk = self._read(length - len(self.held))
                 if chunk:
                     self.held += chunk
                 else:
                     self.sawEOF = True
             if len(self.held) > length:
                 self.held, result = (self.held[length :],
                                      self.held[: length])
             else:
                 self.held, result = '', self.held
             return result

         def pushback(self, somestuff):
             self.held = somestuff + self.held

         def peek(self, length=1):
             data = self.read(length)
             self.pushback(data)
             return data

--Scott David Daniels
scott.daniels at acm.org



More information about the Python-list mailing list