Tuesday, October 19, 2010

Method chaining in python

I have started to learn python again, for a zillionth time now and well I hope that this time I will stick with it and try to use it in practice. While coming home from work I was thinking about an interesting way of doing method chaining in python. I might be wrong and the approach might be incorrect, but  just thought of putting it down in paper before I forget about it.  Anyways by this time of blogging I have realized I pretty much suck with words so won't waste much space on that.

Here's the code:

def method1():
    print "This is method 1"

def method2():
    print "This is method 2"

def method3():
    print "This is method 3"

def method4():
    print "This is method 4"

def noSuchMethod():
    print "No such method"

def methodChainerFunc(obj, listOfMethods):
    """Invokes all the methods provided to it in the list of methods

    If a method does not exist then calls the noSuchMethod"""
    
    for method in listOfMethods:
        getattr(obj,method,noSuchMethod)()
        

if __name__ == "__main__":
    li = ["method1","method2"]
    methodChainerFunc(methodChainer,li)




Couple of interesting things I want to point out are:

1) The function list can be dynamic, so one can specify at the runtime the functions and order in which these functions should be executed though we can have certain tuples that can act as standard order in which the functions should be called. An interesting use case that I can think of is implementing the holder and decorator pattern like this.

2)Also currently the methods don't take any input, but these can be easily modified to take and return the same input so that it can be easily passed around methods with each method modifying it.

May be this whole idea is totally stupid, or may be s.th like this already exists, just thought of putting it out anyways.

No comments: