ActiveState Code

Recipe 498271: chain execution of functions using generators


This is a simple recipe which uses generators to execute a chain of functions. These functions and their argurments are internally present in a list.Here use of generators and properties defined on the result set gives more control to users.

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#!/usr/bin/env python
class chainfunc(list):
    def __init__(self):
        self.res = []
    def append(self, func, *args, **kw):
        super(self.__class__, self).append([func,args,kw])
    def __call__(self):
        for (fn, args, kw) in self:
            retval = (fn.__name__, fn(*args, **kw))
            self.res.append(retval)
            yield retval

    def ANDoperation(self):
        state = reduce(lambda x,y: x and y, [bool for id,bool in self.res])
        return state
    and_operation = property(fget=ANDoperation)

    def ORoperation(self):
        state = reduce(lambda x,y: x or y, [bool for id,bool in self.res])
        return state
    or_operation = property(fget=ORoperation)

# some sample functions

def t1(name,i):
    print name
    print i
    return True

def t2(id,i=False):
    print id
    print i
    return i

if __name__ == '__main__':
    cf = chainfunc()
    cf.append(t1,'hello',2)
    cf.append(t2,'ab_1',False)
    cf.append(t2,'ab_2',True)
    gen = cf()

    # execute all functions
    for i in range(len(cf)):
        print "Function name= %s, function State=%s, "%gen.next()
        print "AND operation =%s, OR operation=%s\n"%(cf.and_operation, cf.or_operation)

Discussion

In the example taken here, there is a group of functions each returning a boolean value. We require different operations to be performed on these functions a) an AND operation of all those return values b) an OR operation of all those return values and results of these define our system. Since the current results of all these functions and their names can be saved in a list, based on manipulation of this result list, various properties can be defined which tell the current status of the system as these functions are executed.

Sign in to comment