docs on for-loop with no __iter__?
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
def __init__(self, infile):
self.infile = infile
self._n = 0
line = self.infile.readline()
if not line:
self._n = self._n + 1
def __getitem__(self, i):
assert i == self._n, "forward iteration only"
x = self.next()
if x is None:
raise IndexError, i
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,
return iter(self.next, None)
dalke at dalkescientific.com
More information about the Python-list