How to make an empty generator?

Xavier Ho contact at xavierho.com
Thu Feb 18 18:35:02 EST 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?

Cheers,
Xav


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>
> 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
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100219/85047607/attachment-0001.html>


More information about the Python-list mailing list