Return self in python

Philip B picture Philip B · Mar 27, 2016 · Viewed 13.7k times · Source

I have a class that represents object. And I have a bunch of methods which modify this object state with no obvious return or obviously without any return. In C# I would declare all these methods as void and see no alternatives. But in Python I am about to make all the methods return self to give myself ability to write awesome one-liners like this:

classname().method1().method2().method3()

Is this Pythonic, or otherwise acceptable in Python?

Answer

Querenker picture Querenker · Mar 27, 2016

Here is a mail from Guido van Rossum (the author of the Python programming language) about this topic: https://mail.python.org/pipermail/python-dev/2003-October/038855.html

I'd like to explain once more why I'm so adamant that sort() shouldn't return 'self'.

This comes from a coding style (popular in various other languages, I believe especially Lisp revels in it) where a series of side effects on a single object can be chained like this:

x.compress().chop(y).sort(z)

which would be the same as

x.compress() x.chop(y) x.sort(z)

I find the chaining form a threat to readability; it requires that the reader must be intimately familiar with each of the methods. The second form makes it clear that each of these calls acts on the same object, and so even if you don't know the class and its methods very well, you can understand that the second and third call are applied to x (and that all calls are made for their side-effects), and not to something else.

I'd like to reserve chaining for operations that return new values, like string processing operations:

y = x.rstrip("\n").split(":").lower()

There are a few standard library modules that encourage chaining of side-effect calls (pstat comes to mind). There shouldn't be any new ones; pstat slipped through my filter when it was weak.