Python Gems #5: silent function chaining

This one is a bit more involved then the last few, because it’s not a specific syntax feature but a way of writing your code.

Take a class, GUIWorker:

class GUIWorker:    
def __init__(self, url):
self.url = url

def click(self):
system.click(self.url)
    def write(self, sentence):      
system.write(self.url, sentence)

If a common use pattern was:

w = GUIWorker('textfield.png')
w.click()
w.write(sentence)

It might make sense to be able to write something like:

w.click().write(sentence)

This is called function chaining. It’s a powerful concept enabled by a very simple internal change:

class GUIWorker:    
def __init__(self, url):
self.url = url

def click(self):
system.click(self.url)
return self
def write(self, sentence):      
system.write(self.url, sentence)
return self

But what if say we have a method, .if_true(predict) and if the predict is true we want to continue the chain — and if not, just ignore the rest of the chain? Introducing: Silent Chain Fail

This is a super powerful (and somewhat ‘magical’) concept. By creating an empty object and overriding its __getattr__ method to return itself if it doesn’t have the requested attribute, you can block off the rest of the call chain without any errors being thrown.


This is a daily series called Python Gems. Each short posts covers a detail or a feature of the python language that you can use to increase your codes readability while decreasing its length.