PEP 255: Simple Generators
gmcm at hypernet.com
Sat Jun 23 18:19:16 CEST 2001
Carsten Geckeler wrote:
>Since we now have "def"/"yield" for generators, the discussion goes more
>or less the same way. You just realizes that generators seem to be to
>complicated for first time Python users. So you decide not to mention
>them at the beginning, but later with the other advanced features.
>So some days later, another friend comes to you. You explain him all
>the basic programming features, but not generators. A week later, the
>friend comes to you again.
>Friend: Well, I programmed a little bit with Python. It really
> be very simple. I have just one problem: I've found a code
> example somewhere on the web and there is a function in it, which
> seems to behave a little bit strange. Perhaps you can help me.
>Me: OK, let me see. Oh, right, this is a generator, not a function!
>Friend: A what? It seems to be like a function but it has some
> statements in it. What does yield do?
Someone: Well, it's kind of like __getitem__ in a class.
Someone: But sometimes you also need __len__, too.
Friend: <walks out>
Someone: Gee, maybe I'm not explaining this well...
The point being that if you start from the iterator protocol,
(and with these changes, ALL "for" loops involve the iterator
protocol), and then explain "yield", it will almost certainly
appear no more magical to your friend than what currently goes
on with making an object sequence-like.
"yield" is a control flow statement, so explaining the control flow
context (rather than focusing on a non-existent definition of "def")
seems a wise idea.
More information about the Python-list