How to make an empty generator?

Robert Kern robert.kern at gmail.com
Fri Feb 19 00:30:54 CET 2010


On Feb 18, 5:08 pm, Steven D'Aprano <st... at REMOVE-THIS-cybersource.com.au> wrote:
 > On 2010-02-18 16:25 PM, Stephen Hansen wrote:
 >
 > > This has to be a stupid question, but :)
 >
 > > I have some generators that do stuff, then start yielding results. On
 > > occasion, I don't want them to yield anything ever-- they're only
 > > really "generators" because I want to call them /as/ a generator as
 > > part of a generalized system.
 >
 > > The only way I can figure out how to make an empty generator is:
 >
 > >      def gen():
 > >          # do my one-time processing here
 >
 > >          return
 > >          yield
 >
 > If all you want is a generator that doesn't yield anything, then surely
 > there isn't any one-time processing and you don't need the comment?

Sure there is. Python doesn't know that nothing gets yielded until it hits the 
return statement before the yield. When it calls .next() on the iterator, the 
code elided by the comment executes, then the return is hit, a StopIteration 
exception is raised, and the iteration is complete.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list