Saturday, July 13, 2013

Using Python decorators for registering callbacks

In my previous post we talked about Python decorators and an intuitive way of remembering how decorators with arguments work.

The following code snippet had triggered the whole chain of thought:

from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return "Hello, World!"
if __name__ == '__main__':
app.run(debug = True)
view raw flask_1 hosted with ❤ by GitHub

Now that we know what decorators with arguments do, which is essentially - calling the decorator factory with the argument, using the argument to make logical branching in the decorator wrapper and returning the wrapper, we can now try to understand the above code. We first move on to the decorator route's source code found here to see it's implementation. Keep the source code opened in a different tab, as we will refer to it in the later sections.

def route(self, rule, **options):
def decorator(f):
endpoint = options.pop('endpoint', None)
self.add_url_rule(rule, endpoint, f, **options)
return f
return decorator


This code deviates a bit from what we think about how decorators are used - decorators wrap the functionality of a target function with certain pre and post actions, like so:

#!/usr/bin/env python
def decorator(func):
def wrapper_around_func():
print "Decorator calling func"
func()
print "Decorator called func"
return wrapper_around_func
@decorator
def func():
print "In the function"
func()
view raw decorator-ex1 hosted with ❤ by GitHub


Output:
 Decorator calling func
 In the function
 Decorator called func

But there isn't any call to the target function index in the route function definition. Instead, this code snippet throws light on another functionality of decorators - registering callbacks.

Callbacks are registered functions which are stored in some container data structure (mostly hashes with key as function name and value as function references). For example,

#!/usr/bin/env python
def func1(arg):
print "calling func1 with arg " + str(arg)
def func2(arg):
print "calling func2 with arg " + str(arg)
callbacks_dict = { 'func1': func1, 'func2': func2 }
callbacks_dict['func1'](1)
callbacks_dict['func2'](2)

Output:
  calling func1 with arg 1
  calling func2 with arg 2

They are useful in building a map of functions and depending on specific user input, the hashes are looked up and the corresponding key's value - which is a function reference is called.