[Tutor] when do I use this? [iterators!]

Karl Pflästerer sigurd at 12move.de
Tue Mar 16 10:55:41 EST 2004


On 16 Mar 2004, Danny Yoo <- dyoo at hkn.eecs.berkeley.edu wrote:

> But it's also possible to iterate across a file:

> ###
>>>> for line in open('/usr/share/dict/words'):
> ...     if line.startswith('py'):
> ...         print line,
> ...

This idiom has one (IMO) great disadvantage: you can't explicitly close
the file.  Maybe someday the for loop will be extended so that files
opened in that way are automagically closed when the loop ends (or
breaks).  Then you could safely open files for reading or writing.

[...]
> So iterators are pretty deeply ingrained in Python.  What's surprising is
> that this hasn't always been so --- iterators were added to the Python
> language in 2001:

And with generators and the itertools module you can write very nice
code (I'm waiting for the generator functions).


   Karl
-- 
Please do *not* send copies of replies to me.
I read the list




More information about the Tutor mailing list