I have an object which defines the iterator interface and also contains a built in file reader (and uses its iterator interface as follows)
class MyIter(object):
def __init__(path):
self.file = open(path, "r")
def next(self):
line = self.file.next()
return line
def __iter__(self):
return self
I call it as:
r = MyIter("path_to_file")
for item in r:
print item
This prints the whole file upto the last line. My question is that I never had to add any check for EOF or check the length of the returned line to specify some end condition. Why does this work?
self.file.next()raisesStopIterationwhen there is no more to iterate. That signals the iteration to end.__iter__implementationreturn self.file.