A decorator in Python is a function that takes another function as its argument, and returns yet another function. Decorators can be extremely useful as they allow the extension of an existing function, without any modification to the original function source code.
Consider the following example:
1. add_together function
The simple add_together function takes 2 integers as arguments and returns the summation of the 2 integer values passed.
1.1. Extending the functionality of add_together with a decorator
Lets propose the following scenario. We would like add_together to be able to take a list of 2 element tuples as its argument and return a list of integers which represents the summation of their values. We can achieve this through the use of a decorator.
Firstly, we give the decorator a sensible name which intimates what its intended purpose is. Here the decorator, called decorator_list is simply a function that takes another function as its argument. This function has been named ‘fnc’ in the arguments list to decorator_list.
Inside the decoratored function, we define a local function called inner. The inner function takes a list of 2-element tuples as its argument. The inner function loops through this list of 2 element tuples, and for each tuple applies the original function, add_together, with index position 0 of the tuple being the argument to a in add_together and index position 1 being the argument to b in add_together. The inner function returns a list of these values summed up. The decorator_list function finally returns the inner function.
Now, let's apply this logic and see how the decorator function works.
To apply the decorator, we use the syntax @, followed by the function name of the decorator above the function that is being decorated. This is syntactically the same as: