How to make an empty generator?

Steven D'Aprano steve at
Fri Feb 19 18:21:03 CET 2010

On Fri, 19 Feb 2010 09:51:54 -0600, Robert Kern wrote:

> On 2010-02-19 00:21 AM, Steven D'Aprano wrote:
>> On Fri, 19 Feb 2010 00:15:20 -0600, Robert Kern wrote:
>>>>> What's the point of the wheel spinning? Did I miss something?
>>>> I wonder whether it's for some kind of framework with a main loop
>>>> like
>>>> for it in list_of_iterables:
>>>>       for x in it:
>>>>           do_this_or_that (x)
>>>> where, every once in a while one wants to throw some arbitrary code
>>>> into the process, in the form of an empty iterable with side effects.
>>> Yes. That is exactly what the OP said in his original post:
>>> """
>>> 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. """
>> But he doesn't say anything about side-effects.
> "I have some generators *that do stuff*, then start yielding results."
> [emphasis mine]. 

What does "do stuff" have to do with side-effects? Here's a generator 
that does stuff, and it has no side-effects.

def generator_that_does_stuff(x):
    y = 3*x**2 - 5*x + 1
    yield y

"Do stuff" is ambiguous -- it could mean stuff with side-effects, or 
stuff without. The first is potentially harmful, the second is pointless.

> Then he gives an example of a generator that does
> side-effect stuff and returning before yielding anything.

Unfortunately the OP's original post isn't visible to me, so I can only 
respond to your post, which may or may not quote the entire original post.

The only example I have seen was an empty generator with a comment saying 
"do my one-time processing here", with *no* indication of what that one-
time processing is supposed to be, why it is necessary, and whether it 
has side-effects or not.

Since the OP (apparently) hasn't seen fit to comment, we're still all 
guessing what he means. It's certainly possible, likely even, that he's 
using generators that operate by side-effect: that explanation is 
consistent with his request. Personally, I can't imagine that would be 
good coding practice, but I could be wrong.


More information about the Python-list mailing list