How to make an empty generator?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Feb 19 00:08:32 CET 2010


Sorry for breaking the threading, but Stephen's original post hasn't come 
through to my provider.

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?


>> Is there a better way? The return/yield just makes me flinch slightly.

Meh. An empty generator is a funny thing to do, so it's not bad that it 
reads a bit funny. I don't have a problem with it.

If it really annoys you, you could do this:

def empty():
    for x in []:
        yield



-- 
Steven



More information about the Python-list mailing list