Calling a generator multiple times
Tim Peters
tim.one at home.com
Sun Dec 9 11:47:14 EST 2001
[Steven Majewski]
> ...
> And when you use these generators in a for loop, they two bits of
> confusion seem to cancel each other out. "for i in g(10):" really
> behaves just like it's definition. I'm guessing that this fact
> was one of the selling points for this syntax -- that if you didn't
> look under the hood and just USED them, they would not be confusing.
Yes it was, just as the low-level details of __getitem__ and IndexError in
the pre-2.2 iteration protocol remain blissfully unknown to most Python
programmers. The driving force in both cases was to make "for ... in ..."
work smooth as phlegm on a brass doorknob, despite that phlegm and brass
doorknobs aren't all that attractive in isolation <wink>.
> I'm not sure that supposition has been born out, but they do get
> less confusion with use.
All evidence to date says people learn how to use generators in the for-loop
context easily. If they're going to use .next() explicitly, then they have
some conceptual work to do -- even if they're not mucking with generators.
> Perhaps it would be better to spend another keyword, along with
> 'def' and 'class' , to distinguish 'generator factories'.
In practice, starting the docstring with "Generate ..." instead of "Return
..." is clear enough.
> ...
> Generators, functions and methods are just slight variations on each
> other.
Absolutely. People should consider *all* callable objects in 2.2 to be
generators -- it's just that if the body doesn't contain "yield", then the
language helpfully calls .next() once for you by magic <wink>.
More information about the Python-list
mailing list