Re: Help me understand this iterator
- From: Steven D'Aprano <steve@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx>
- Date: Tue, 31 Oct 2006 23:02:17 +1100
On Tue, 31 Oct 2006 03:36:08 -0800, LaundroMat wrote:
Hi,
I've found this script over at effbot
(http://effbot.org/librarybook/os-path.htm), and I can't get my head
around its inner workings.
[snip code]
Now, if I look at this script step by step, I don't understand:
- what is being iterated over (what is being called by "file in
DirectoryWalker()"?);
What is being iterated over is the list of files in the current directory.
In Unix land (and probably DOS/Windows as well) the directory "." means
"this directory, right here".
- where it gets the "index" value from;
When Python see's a line like "for x in obj:" it does some special
magic. First it looks to see if obj has a "next" method, that is, it
tries to call obj.next() repeatedly. That's not the case here --
DirectoryWalker is an old-style iterator, not one of the fancy new ones.
Instead, Python tries calling obj[index] starting at 0 and keeps going
until an IndexError exception is raised, then it halts the for loop.
So, think of it like this: pretend that Python expands the following code:
for x in obj:
block
into something like this:
index = 0
while True: # loop forever
try:
x = obj[index]
block # can use x in block
except IndexError:
# catch the exception and escape the while loop
break
index = index + 1
# and now we're done, continue the rest of the program
That's not exactly what Python does, of course, it is much more efficient,
but that's a good picture of what happens.
- where the "while 1:"-loop is quitted.
The while 1 loop is escaped when the function hits the return statement.
--
Steven.
.
- References:
- Help me understand this iterator
- From: LaundroMat
- Help me understand this iterator
- Prev by Date: Re: Where do nested functions live?
- Next by Date: Re: Help me understand this iterator
- Previous by thread: Re: Help me understand this iterator
- Next by thread: Re: Help me understand this iterator
- Index(es):
Relevant Pages
|