method chaining in python

robert king picture robert king · Aug 29, 2012 · Viewed 23.1k times · Source

(not to be confused with itertools.chain)

I was reading the following: http://en.wikipedia.org/wiki/Method_chaining

My question is: what is the best way to implement method chaining in python?

Here is my attempt:

class chain():
    def __init__(self, my_object):
        self.o = my_object

    def __getattr__(self, attr):
        x = getattr(self.o, attr)
        if hasattr(x, '__call__'):
            method = x
            return lambda *args: self if method(*args) is None else method(*args)
        else:
            prop = x
            return prop

list_ = chain([1, 2, 3, 0])
print list_.extend([9, 5]).sort().reverse()

"""
C:\Python27\python.exe C:/Users/Robert/PycharmProjects/contests/sof.py
[9, 5, 3, 2, 1, 0]
"""

One problem is if calling method(*args) modifies self.o but doesn't return None. (then should I return self or return what method(*args) returns).

Does anyone have better ways of implementing chaining? There are probably many ways to do it.

Should I just assume a method always returns None so I may always return self.o ?

Answer

Zaur Nasibov picture Zaur Nasibov · Aug 29, 2012

There is a very handyPipe library which may be the answer to your question. For example::

seq = fib() | take_while(lambda x: x < 1000000) \
            | where(lambda x: x % 2) \
            | select(lambda x: x * x) \
            | sum()