Re: Help me understand this iterator



LaundroMat wrote:

[me hitting send too soon]

Now, if I look at this script step by step, I don't understand:

- where the "while 1:"-loop is quitted.

class DirectoryWalker:
# a forward iterator that traverses a directory tree

def __init__(self, directory):
self.stack = [directory]
self.files = []
self.index = 0

def __getitem__(self, index):
while 1:
try:
file = self.files[self.index]
self.index = self.index + 1
except IndexError:
# pop next directory from stack
self.directory = self.stack.pop()

If self.stack is empty, pop() will raise an IndexError which terminates both
the 'while 1' loop in __getitem__() and the enclosing 'for file in ...'
loop

self.files = os.listdir(self.directory)
self.index = 0
else:
# got a filename
fullname = os.path.join(self.directory, file)
if os.path.isdir(fullname) and not
os.path.islink(fullname):
self.stack.append(fullname)
return fullname

The return statement feeds the next file to the for loop.

Peter

.



Relevant Pages

  • Re: Loop in a loop?
    ... I want to do a loop in a loop. ... for each_iterable in iterables: ... for i in zip(array1, array2, array3): ... except IndexError: pass ...
    (comp.lang.python)
  • RE: Looking at the next element in a for loop
    ... #- Is there a way I can get the next element in the loop? ... Traceback: ... IndexError: list index out of range ...
    (comp.lang.python)