Method chaining

Peter Otten __peter__ at web.de
Fri Nov 22 10:20:03 EST 2013


Steven D'Aprano wrote:

> 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 

That cuts both ways ;)

> 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. 

I've not yet run short of vertical space ;)

> Chained method calls is idiomatic in some languages. 

Languages with mutable objects?

> 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()

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

OK, that one is disgusting...

Anyway, I'd like to see a sequence of method names taken from actual code 
that profits from this chaining pattern.




More information about the Python-list mailing list