How to make an empty generator?

Robert Kern robert.kern at gmail.com
Thu Feb 18 19:20:49 EST 2010


On 2010-02-18 17:36 PM, Stephen Hansen wrote:
> On Thu, Feb 18, 2010 at 2:56 PM, Robert Kern <robert.kern at gmail.com
> <mailto:robert.kern at gmail.com>> wrote:
>
>     class once(object):
>         def __init__(self, func, *args, **kwds):
>             self.func = func
>             self.args = args
>             self.kwds = kwds
>
>         def __iter__(self):
>             return self
>
>         def next(self):
>             self.func(*self.args, **self.kwds)
>             raise StopIteration()
>
>
> Hmm, yeah. I'd probably tweak it into a decorator and name it
> sideeffect_only or something, but yeah, that's the right approach at least.

Well, with a decorator, you could even use the cringeworthy return/yield syntax 
while keeping it hidden from your users (not to mention reducing the amount of 
boilerplate people need to write).


from functools import wraps

def sideeffect_only(func):
     @wraps(func)
     def wrapper(*args, **kwds):
         func(*args, **kwds)
         # Some helpful comment about why there is a return/yield.
         return
         yield
     return wrapper


But you can also write one where the wrapper() returns a once() instance. It 
might be useful to use the once class instead of a generator such that you can 
write code that distinguishes side-effect only iterators from other iterators in 
your system. It might be useful for debugging if nothing else.

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