Introduction to decorators
Decorators introduce a programming paradigm that is not found in statically linked languages, like C++ or Java. Taking advantage of closures and the fact that functions are first class citizens of python, we can easily change the behaviour of them adding a single line of code.
If you have not used dynamic languages before, chances are that you cannot immediately see the value of decorators but as you will learning about them chances are that you are going to change the way you write and think about coding, as you will discover more elegant and efficient ways to implement things that are either very verbose or even impossible to code in traditional statically linked languages. Although there is a small learning curve associated with them, decorators will quickly pay back enough dividend to justify the learning process.
A python decorator is nothing else than a callable object, receiving a callable as a parameter and returning another callable as its return value.
We will start with the simplest possible case of a decorator, which consists of a regular function accepting a function as its parameter, defining a nested function taking the same parameters as the passed one, returning the nested function to the caller.
What I have just described above, can be visualized in the following picture which presents the basic blocks of a python decorator:
In the following page we will delve in a bit deeper to the concept of decorators, writing a very simplistic program presenting their use.