How to make an empty generator?

Ben Finney ben+python at benfinney.id.au
Thu Feb 18 19:33:00 EST 2010


Arnaud Delobelle <arnodel at googlemail.com> writes:

> What about
>     foo = iter('')

That doesn't return a generator.

    >>> foo = iter('')
    >>> foo
    <listiterator object at 0xf7cd3ed0>

Whether the OP needs to create a generator, or just any iterable type,
isn't clear.


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

> He doesn't want *any* empty generator. He wants an iterator that
> executes some given side-effect-producing code then immediately raises
> the StopIteration.

Ah, hm. That's a rather perverse use case, but I'm sure the OP has their
reasons. It's going to confuse a reader who isn't expecting it, no
matter how simply it's done.

So, I think the best answer is what has already been suggested, but that
it's perverse enough that the hack *needs* a comment to say why it's
being done.

    def make_empty_generator_with_side_effect():
        """ Make a generator that does important work, but is empty. """

        # Do the important work here.
        spam = object()

        # Make this function return an empty generator.
        if False: yield

-- 
 \              “When cryptography is outlawed, bayl bhgynjf jvyy unir |
  `\                                              cevinpl.” —Anonymous |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list