Interesting little "gotcha" with generators

Kenneth McDonald kenneth.m.mcdonald at sbcglobal.net
Thu Dec 22 16:59:55 EST 2005


I recently had need to write the following code:

     def compileOuter(self):
         if False: yield None
         else: return

"compileOuter" is a generator function which is implemented in  
various classes. In this particular class, it always yields nothing.  
However, none of the following work:

     def compileOuter(self):
         return

     def compileOuter(self):
         pass

     def compileOuter(self):
         yield

The first two don't work because in order to define a generator, you  
must have a yield statement inside it. The last doesn't work because  
every "yield" must have an argument.

I've been using "return" in generators ever since I started using  
generators, but on reflection, it seems to me that such a thing is in  
some ways inconsistent; "return" is (conceptually, at least  
originally) a function statement, where "return" by itself really  
stands in for "return None". But in generators, it is being used as a  
control flow command. For example, you can't have "return" with an  
argument inside a generator.

Too bad "return" wasn't entirely forbidden within generators, and  
"yield" without an argument mandated instead. Oh well, too let now I  
suppose...


Cheers,
Ken



More information about the Python-list mailing list