Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Generator functions subclass generator?

Reply
Thread Tools

Generator functions subclass generator?

 
 
Terry Reedy
Guest
Posts: n/a
 
      06-18-2009
An iterator class is a class with an __iter__ method that returns self
and a __next__ method that on each call returns one not-yet-returned
item of the actual or virtual collection it represents and raises
StopIteration when there are no more items to return. 'Generator' (3.1
name) is one of several built-in iterator classes.

A generator function is a function with keyword 'yield' in its body. Its
presence results in four special behaviors.
1. When the generator function is called, it returns a generator
instance inst instead of executing its body code.
2. When inst.__next__ is called, the body *is* executed.
3. When any yield is reached, an object is returned (yielded), but
execution of the body code is only suspended, not terminated.
4. The next call resume execution at the point of suspension.

I believe any non-recursive generator functions can be written as an
actual iterator class, though perhaps with more difficulty. (I suspect
the same is true of recursive generators but I have never tried one.)
The greater ease of writing gfs is one reason we have them.

I find the first two bits of magic easier with the following simile:
a generator function is like a virtual subclass of generator.

In other words,

def gf(params):
body

acts somewhat like the following hypothetical code

class gf(generator):
# inherited __new__ method stores the args
# __iter__ is also inherited
def __next__():
params = <stored args> # added
body

'yield' in the body of __next__ would still have special effects 3 and 4.

I am planning to use this in my book. Does anyone else, particularly
Python beginners, find it helpful?

Terry Jan Reedy


 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Subclass of subclass Fab C++ 0 08-09-2012 09:54 AM
subclass a class in the namespace of the that subclass Trans Ruby 8 10-23-2008 07:24 AM
String subclass method returns subclass - bug or feature? S.Volkov Ruby 2 03-12-2006 06:46 PM
subclass has a variable that is subclass of same superclass jstorta Java 3 02-20-2006 08:42 PM
please help me in distinguish redefining functions, overloading functions and overriding functions. Xiangliang Meng C++ 1 06-21-2004 03:11 AM



Advertisments