Help me understand this iterator

Peter Otten __peter__ at web.de
Tue Oct 31 07:02:34 EST 2006


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




More information about the Python-list mailing list