Python Decorators are important features of the language that allow a programmer to modify the behavior of a class. These features are added functionally to the existing code. This is a type of metaprogramming when the program is modified at compile time. The decorators can be used to inject modified code in functions or classes. The decorators allow the program to be modified to add any code that has a special role to play. Decorators are called before the definition of the function you have decorated.
The use of decorators could be explained with the following example. Suppose we write a program to “Decorate” a function using another function. the code goes like:
def decorating(function):
def item():
print ( "The function was decorated." )
function()
return item
def my_function():
print ( "This is my function." )
my_function()
decorate = decorating(my_function)
decorate()
|
Output
This is my function.
The function was decorated.
This is my function.
Firstly, “This is my function” appears because of the function call my_function(). The second set of output was because of the Decorating function.
The same thing can also be done by using decorators. The following code explains that. Note that the decorating statement is defined above the function to be decorated.
def decorating(function):
def item():
print ( "The function was decorated." )
function()
return item
@decorating
def my_function():
print ( "This is my function." )
my_function()
|
Output
The function was decorated.
This is my function.
The call() decorator
The call() decorator is used in place of the helper functions. In python, or in any other languages, we use helper functions for three major motives:
- To identify the purpose of the method.
- The helper function is removed as soon as its job is completed. And
- The purpose of helper function matches with that of decorator function.
The following example will illustrate the significance of the call decorator method. In this example, we would be building a list of the doubles of the first “n” numbers, using a helper function.
The code is as follows:
def list_of_numbers(n):
element = []
for i in range (n):
element.append(i * 2 )
return element
list_of_numbers = list_of_numbers( 6 )
print ( len (list_of_numbers),
list_of_numbers[ 2 ])
|
Output
6, 4
The above code could also be written using the call() decorator:
def call( * argv, * * kwargs):
def call_fn(function):
return function( * argv, * * kwargs)
return call_fn
@call ( 6 )
def list_of_numbers(n):
element = []
for i in range (n):
element.append(i * 2 )
return element
print ( len (list_of_numbers),
list_of_numbers[ 2 ])
|
Output
6, 4
As it is observed, that the output is same as before, this means that the call() decorator works almost exactly like helper functions.