How to make an empty generator?

Robert Kern robert.kern at gmail.com
Fri Feb 19 17:00:45 CET 2010


On 2010-02-19 01:01 AM, Ben Finney wrote:
> Robert Kern<robert.kern at gmail.com>  writes:
>
>> On 2010-02-18 18:33 PM, Ben Finney wrote:
>>> 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.
>>
>> Which he explained fairly clearly, I thought, in his original post.
>
> (The original post isn't available to me; the reference in your reply
> isn't accessible AFAICT.)

You responded to my post which quoted his in full.

> In the part of the original that you quoted, he speaks only of empty
> generators (easy and clean), not generators that exist only for the
> purpose of side-effects without yielding any items.

"""
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.

...

      def gen():
          # *do my one-time processing here*

          return
          yield
"""
[emphasis mine]

Seriously, it's all there. I'm rather appalled at the lack of reading 
comprehension demonstrated in this thread.

> It's that latter that I describe as perverse, and I would think it worth
> some effort to determine if that can be avoided by a different approach.

By rearchitecting the system to accept things that aren't iterators, yes. But he 
may not be in control of that system. And it may not make things cleaner to do 
so if he wants to use itertools to compose the iterables, whether they are for 
side effects or not, in various ways.

-- 
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