grokking generators and iterators

Andrew Dalke dalke at dalkescientific.com
Sat May 11 02:27:30 EDT 2002


Bob Horvath:
>How would you suggest writing a generator that spits out 5 line chunks
>of a file at a time?
>
>How would you do it without generators?

David Eppstein answered the first.

As to the second, here's an (untested) example

class FiveAtATime:
  def __init__(self, file):
    self.file = file
  def next(self):
    # To iterate manually, and allow iter
    s = self.file.readline()
    if not s:
      return None
    data = [s]
    for i in range(4):
      data.append(self.file.readline())
    return data
  def __getitem__(self, i):
    # To allow use in for loops
    x = self.next()
    if x is None:
      raise IndexError(i)
    return x
  def __iter__(self):
    # For new-style iters
    return iter(self, None)

This can be used as

  reader = FiveAtATime(open("input.txt"))
  while 1:
    x = reader.next()
    if x is None:
      break
    ...

or as

  for x in FiveAtATime(open("input.txt")):
    ...

You can see, it's rather more complicated than using yield.

                    Andrew
                    dalke at dalkescientific.com






More information about the Python-list mailing list