docs on for-loop with no __iter__?

Andrew Dalke adalke at mindspring.com
Sat Sep 4 23:32:21 CEST 2004


Steven Bethard wrote:
> Presumably there was a reason not to use len() to determine
> the end of the sequence?

Because that allows iteration over things where
you don't yet know the size.  For example, reading
lines from a file.  Here's how it could have been
done using Python 1.x

class FileReader:
   def __init__(self, infile):
     self.infile = infile
     self._n = 0

   def next(self):
     line = self.infile.readline()
     if not line:
         return None
     self._n = self._n + 1
     return line

   def __getitem__(self, i):
     assert i == self._n, "forward iteration only"
     x = self.next()
     if x is None:
         raise IndexError, i
     return x

I used the _n to double check that people don't
think it's a random access container.

Support for Python 2.x iterators was easy,

   def __iter__(self):
     return iter(self.next, None)

				Andrew
				dalke at dalkescientific.com



More information about the Python-list mailing list