Interesting little "gotcha" with generators

Duncan Booth duncan.booth at invalid.invalid
Thu Dec 22 17:09:34 EST 2005


Kenneth McDonald wrote:

> 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
> 

This would work:

  def compileOuter(self):
    	return iter(())

and depending on how it is used, you might also get away with:

  def compileOuter(self):
    return []

A generator is simply a function which when called returns an iterator, so 
you can use any other function which returns an iterator in its place.



More information about the Python-list mailing list