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:


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.



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:



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,


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.