How to make an empty generator?

Ben Finney ben+python at benfinney.id.au
Fri Feb 19 00:33:00 CET 2010


Robert Kern <robert.kern at gmail.com> writes:

> On 2010-02-18 16:25 PM, Stephen Hansen wrote:
> > The only way I can figure out how to make an empty generator is:
> >
> >      def gen():
> >          # do my one-time processing here
> >
> >          return
> >          yield
> >
> > Is there a better way? The return/yield just makes me flinch
> > slightly. I tried just raising StopIteration at the end, but of
> > course that didn't work.

No need to define functions or classes; let a generator expression take
care of it for you::

    >>> foo = (x for x in list())
    >>> foo.next()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    StopIteration

-- 
 \           “Value your freedom or you will lose it, teaches history. |
  `\     “Don't bother us with politics,” respond those who don't want |
_o__)                               to learn.” —Richard Stallman, 2002 |
Ben Finney



More information about the Python-list mailing list