Return self in python

If you so desire, you can use a decorator here. It will stand out to someone looking through your code to see the interface, and you don't have to explicitly return self from every function (which could be annoying if you have multiple exit points).

import functools


def fluent(func):
    @functools.wraps(func)
    def wrapped(*args, **kwargs):
        # Assume it's a method.
        self = args[0]
        func(*args, **kwargs)
        return self
    return wrapped


class Foo(object):
    @fluent
    def bar(self):
        print("bar")

    @fluent
    def baz(self, value):
        print("baz: {}".format(value))

foo = Foo()
foo.bar().baz(10)

Prints:

bar
baz: 10

It is an excellent idea for APIs where you are building state through methods. SQLAlchemy uses this to great effect for example:

>>> from sqlalchemy.orm import aliased
>>> adalias1 = aliased(Address)
>>> adalias2 = aliased(Address)
>>> for username, email1, email2 in \
...     session.query(User.name, adalias1.email_address, adalias2.email_address).\
...     join(adalias1, User.addresses).\
...     join(adalias2, User.addresses).\
...     filter(adalias1.email_address=='[email protected]').\
...     filter(adalias2.email_address=='[email protected]'):
...     print(username, email1, email2)

Note that it doesn't return self in many cases; it will return a clone of the current object with a certain aspect altered. This way you can create divergent chains based of a shared base; base = instance.method1().method2(), then foo = base.method3() and bar = base.method4().

In the above example, the Query object returned by a Query.join() or Query.filter() call is not the same instance, but a new instance with the filter or join applied to it.

It uses a Generative base class to build upon; so rather than return self, the pattern used is:

def method(self):
    clone = self._generate()
    clone.foo = 'bar'
    return clone

which SQLAlchemy further simplified by using a decorator:

def _generative(func):
    @wraps(func)
    def decorator(self, *args, **kw):
        new_self = self._generate()
        func(new_self, *args, **kw)
        return new_self
    return decorator

class FooBar(GenerativeBase):
    @_generative
    def method(self):
        self.foo = 'bar'

All the @_generative-decorated method has to do is make the alterations on the copy, the decorator takes care of producing the copy, binding the method to the copy rather than the original, and returning it to the caller for you.


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.


Here is an example which demonstrates a scenario when it may be a good technique

class A:
    def __init__(self, x):
        self.x = x
    def add(self, y):
        self.x += y
        return self
    def multiply(self, y):
        self.x *= y
        return self
    def get(self):
        return self.x
a = A(0)
print a.add(5).mulitply(2).get()

In this case you are able to create an object in which the order in which operations are performed are strictly determined by the order of the function call, which might make the code more readable (but also longer).