Method chaining

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Nov 22 15:26:17 CET 2013


On Fri, 22 Nov 2013 13:08:03 +0100, Peter Otten wrote:

> These things are nice to write as long as you omit the gory details, but
> personally I don't want to see the style it favours in my or other
> people's code.

There's not really a lot of difference between:

    obj = MyClass()
    obj.spam()
    obj.eggs()
    obj.cheese()

and

    obj = MyClass().spam().eggs().cheese()


except the first takes up a lot more vertical space. Chained method calls 
is idiomatic in some languages. If there is a problem with it, it is that 
it doesn't make it clear that each method call is being used only for its 
side-effects, rather than it being a series of distinct objects. But in 
my opinion that flaw is a very minor one.

The nice thing about using an explicit method chaining call rather than 
building your class to support it by default is that the initial call to 
the adaptor signals that everything that follows is called only for the 
side-effects.

    obj = chained(MyClass()).spam().eggs().cheese()



-- 
Steven



More information about the Python-list mailing list