[Biopython-dev] iterators
Andrew Dalke
dalke at acm.org
Wed Apr 25 16:39:29 EDT 2001
Anyone catch the recent discussions of adding better
iteration support for Python? Most specifically, Tim Peter's
post in c.l.py named "Iterators, generators and 2.2"?
Old way was that
for x in spam:
pass
was semantically identical to (excepting the exposure of the
loop counter)
i = 0
while 1:
try:
x = spam[i]
except IndexError:
break
... work with x ...
New way is more like
class IterAdapter:
def __init__(self, list):
self.list = list
self.i = 0
def next(self):
try:
x = self.list[self.i]
except IndexError:
raise StopIteration
self.i += 1
if hasattr(spam, "__iter__"):
iter = spam.__iter__()
else:
iter = IterAdapter(spam)
while 1:
try:
x = iter.next()
except StopIteration:
break
... work with x ...
This simplifies a lot of the code I've done, which turns
constructs like:
class LineReader:
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 self._n == i, "forward iteration only"
x = self.next()
if x is None:
raise IndexError, i
return x
into
class IterUntilNone:
def __init__(self, obj):
self.obj = obj
def next(self):
x = self.obj.next()
if x is None
raise StopIteration
return x
class LineReader:
def __init__(self, infile):
self.infile = infile
def next(self):
line = self.infile.readline()
if not line:
return None
return line
def __iter__(self):
return IterUntilNone(self)
and where that 'IterUntilNone' (got a better name?) can be shared
across a range of classes, rather than having to code up
the '_n' solution in every one. (I suppose I could have
derived from a ForwardIterator class, but that never worked
out well in my mind - too complicated)
I like. But that has to wait for 2.2 to come out ;(
Andrew
dalke at acm.org
More information about the Biopython-dev
mailing list