Series generator using multiple generators & function decorators

This is a rewrite of my previous recipe http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/389202. Instead of returning the series as a list, this one creates another generator instead.


The only difference between this and the original recipe is that the series function ultimately returns a generator for the series here, not the final list.

So it should be used like...

for item in series(condition=lambda x: x, process=lambda x: x*x, number=100): do_whatever_with(item)

This could be more useful than the original recipe, since the result is a custom generator for the kind of series you want, with the required size.

# Simple series generator with
# multiple generators & decorators.
# Author : Anand B Pillai

def myfunc(**kwds):

    def func(f):
        cond = kwds['condition']
        proc = kwds['process']
        num = kwds['number']

        x = 0
        for item in f():
            
            if cond and cond(item):
                if proc: item = proc(item)
                yield item
                x += 1
                
            if x==num:
                break

    return func

def series(condition=None, process=None, number=10):

    @myfunc(condition=condition,process=process,number=number)    
    def wrapper():
        x = 1
        while 1:
            yield x
            x += 1

    return wrapper

code.activestate.com ↗