How to make an empty generator?
contact at xavierho.com
Fri Feb 19 00:35:02 CET 2010
I don't think it's a stupid question at all. =]. But wouldn't it solve the
problem if you call the generator the first time you need it to yield?
On Fri, Feb 19, 2010 at 9:30 AM, Robert Kern <robert.kern at gmail.com> wrote:
> On Feb 18, 5:08 pm, Steven D'Aprano <st... at REMOVE-THIS-cybersource.com.au>
> > 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
> that is made terrible by our own mad attempt to interpret it as though it
> an underlying truth."
> -- Umberto Eco
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-list