Suggested amendment to PEP 255

Greg Ewing greg at cosc.canterbury.ac.nz
Wed Jun 20 01:55:28 EDT 2001


Tim Peters wrote:
> 
> Who would this help?  Seriously.  There's nothing special about a generator
> to a caller, except that it returns an object that implements the iterator
> interface.

What matters to the caller is irrelevant here. We're talking
about what matters to someone writing or reading the 
implementation. To those people, there is a VERY big 
difference between a regular function and a 
generator-function -- about as big as the difference 
between a class and a function!

In fact, a generator-function is in many ways much more
like a class than a function. Calling a generator-function
doesn't execute any of the code in its body; instead, it
creates an instance of the generator, much like calling
a class creates an instance of the class. Calling them
"generator classes" and "generator instances" would
perhaps be more appropriate, and more suggestive of the
way they actually behave.

The more I think about this, the more I agree with those
who say that overloading the function-definition syntax
for defining generators is a bad idea. It seems to make
about as much sense as saying that there shouldn't be
any special syntax for defining a class -- the header
of a class definition should look exactly like a function
definition, and to tell the difference you have to look
for some subtle clue further down.

I suggest dropping the "def" altogether and using:

  generator foo(args):
    ...
    yield x
    ...

Right from the word go, this says loudly and clearly
that this thing is *not* a function, it's something else.
If you haven't come across generators before, you go and
look in the manual to find out what it means. There
you're told something like

   Executing a generator statement creates a special
   callable object called a generator. Calling a generator
   creates a generator-instance, which is an iterator
   object... [...stuff about the "yield" statement...]

I think this is going to be easier to document and lead
to much less confusion than trying to explain the magic
going on when you call something that looks for all the
world like a function and it doesn't execute any of the
code in it.

Explicit is better than implicit!

-- 
Greg Ewing, Computer Science Dept, University of Canterbury,	  
Christchurch, New Zealand
To get my email address, please visit my web page:	  
http://www.cosc.canterbury.ac.nz/~greg



More information about the Python-list mailing list