How to make an empty generator?

Mel mwilson at the-wire.com
Thu Feb 18 20:28:49 EST 2010


Steven D'Aprano wrote:

> On Thu, 18 Feb 2010 17:30:54 -0600, Robert Kern wrote:
> 
>>  > 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.
> 
> I don't understand why you care about having *any* code before the
> StopIteration. That's like:
> 
> def empty():
>     for x in range(1000):
>         pass # Spin wheels uselessly
>     return
>     yield
> 
> 
> 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.

	Mel.





More information about the Python-list mailing list