Calling a generator multiple times

Oren Tirosh oren-py-l at hishome.net
Sat Dec 8 11:44:19 CET 2001


On Sat, Dec 08, 2001 at 12:30:25AM +0000, Courageous wrote:
> 
> >A generator is a function or method that -- by virtue of using the yield
> >statement -- 
> 
> I understand how it works, intuitively. My objection is not that
> I don't understand it, but rather that a lone keyword appearing
> in the content of the method definition actually changes what is
> being defined. That's just plain wrong.

I agree.  It should be immediately apparent that a generator function is 
not a regular instance of the 'function' type.  I believe that the most 
natural way to indicate this is to use the function object's type.  A 
generator function should be an instance of a 'generator' type, a subclass 
of the 'function' type.  It should return a 'generator_iterator' object 
when called.

Here's what the syntax might look like:

  def foo(args)(generator): ...

Why this syntax?  Simply following the same rules as class definitions.  
A class definition has an optional base class or classes in parens; when 
omitted, a default metaclass is used ('class' today, perhaps 'object' 
in the future).  This syntax is the logical result of extending this rule
to functions and defining 'function' as the default metaclass for new 
function definitions.  This default may be overridden, with the only 
alternative being 'generator', at least for now.  There are no new keywords 
required, 'generator' is just a built-in type.

The __future__ mechanism gives a clean way to deprecate the current syntax
where a generator function is defined by the mere presence of a 'yield'
statement somewhere within the function's body.

	Oren





More information about the Python-list mailing list