How to make an empty generator?
Robert Kern
robert.kern at gmail.com
Fri Feb 19 01:15:20 EST 2010
On 2010-02-18 19:28 PM, Mel wrote:
> 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.
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.
"""
--
Robert Kern
"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
More information about the Python-list
mailing list