Python: jQuery-like function chaining?

Blender picture Blender · Dec 3, 2010 · Viewed 7.4k times · Source

I couldn't find anything on this subject on Google, so I think I should ask it here:

Is it possible to chain functions with Python, like jQuery does?

['my', 'list'].foo1(arg1, arg2).foo2(arg1, arg2).foo3(arg1, arg2) #etc...

I am losing a lot of space and readability when I write this code:

foo3(foo2(foo1(['my', 'list'], arg1, arg2), arg1, arg2), arg1, arg2) #etc...

There seems to exist some illusive library for creating such functions, but I can't seem to see why this has to be so complicated-looking...

Thanks!

Answer

camel_space picture camel_space · Dec 3, 2010

As long as the function returns a value, you can chain it. In jQuery, a selector method usually returns the selector itself, which is what allows you to do the chaining. If you want to implement chaining in python, you could do something like this:

class RoboPuppy:

  def bark(self):
    print "Yip!"
    return self

  def growl(self):
    print "Grr!"
    return self

pup = RoboPuppy()
pup.bark().growl().bark()  # Yip! Grr! Yip!

Your problem, however, seems to be that your function arguments are too cramped. Chaining is not a solution to this. If you want to condense your function arguments, just assign the arguments to variables before passing them to the function, like this:

spam = foo(arg1, arg2)
eggs = bar(spam, arg1, arg2)
ham = foobar(eggs, args)