Method Chaining

Michael Selik michael.selik at gmail.com
Fri Jun 17 09:34:33 EDT 2016


On Fri, Jun 17, 2016 at 5:31 AM Steven D'Aprano <steve at pearwood.info> wrote:

> (g.move_to((p1 + p2a) / 2)
>   .line_to(p1 + (p2 - p1) * frac)
>   .line_to((p1 + p1a) / 2)
>   .stroke()
>   )
>
> the parens and indentation more clearly mark this chunk of code as a
> unit.


I prefer reserving indentation for where they're required ("for", "while",
"if", etc.). In this case, I'd use an extra blank line before and after.
Or, better, I'd move the chunk of code into a function by itself.

On the other hand, I like the fact that methods which are
> conceptually procedures that operate by side-effect return None.
>

Exactly. The chained version looks like each method is returning a modified
copy. The Pandas library isn't perfect, but it has a good consistency for
methods returning copies unless explicitly "inplace=True", in which case
the method returns None.

Paraphrasing Jakob's law of user experience [0], it doesn't matter if your
design is better. People are more familiar with the design of other
libraries and will expect yours to behave the same way: impure methods
return None, unless named "pop" or a similar standard.

[0] https://www.nngroup.com/articles/end-of-web-design/



More information about the Python-list mailing list