2.2 features

Tim Peters tim.one at home.com
Wed Jul 25 17:51:16 EDT 2001

[Nick Perkins]
> I like generators a lot.  Here's a fun one:
> #------ begin code
> [snip]
> if __name__ == "__main__":
>     g = fib()
>     for i in range(9):
>         print g.next(),
> #------ end code

[Jeff Shannon]
> Haven't looked into this in detail, or even downloaded 2.2 yet, but...
> couldn't that be written as:
> if __name__ == '__main__':
>     for i in fib():
>         print i,
> ???

The difference is that you never stop printing, but the earlier code printed
only 9 of them.

> (being under the impression that the main point of iterators is
> convenient for-loop usage...)

Indeed it is, and generators are just another flavor of iterator; explicit
use of .next() should rarely be needed (yet neither feared <wink>).  Another
way to write the "only 9" loop:

count = 0
for f in fib():
    print f,
    count += 1
    if count >= 9:

That's something of a strain in such a simple case, but in general the
ability to "get out of a loop early" without needing to materialize the
whole sequence first is a major practical application of the iterator

for statement in python_program.parse():
    if statement.kind is FUTURE_STMT:
        print "Start a flamewar about", str(statement)

More information about the Python-list mailing list