Python decorator is a function that helps to add some additional functionalities to an already defined function. Python decorator is very helpful to add functionality to a function that is implemented before without making any change to the original function. Decorator is very efficient when want to give an updated code to an existing code.
Hope all of you are fine and spending a very good time with python. Today we will learn about python decorator. As I defined earlier, python decorator is nothing but a decorator that decorates a function. For example, you have a flower vase in your home. Now you want to decorate it with some flower and some ornaments. Then you will be called as decorator and the flower and ornaments will be called additional functionalities.
Python Decorator Basic Structure
Let’s have a look at the basic structure of a python decorator function.
# example of decorator def sampleDecorator(func): def addingFunction(): # some new statments or flow control print("This is the added text to the actual function.") # calling the function func() return addingFunction @sampleDecorator def actualFunction(): print("This is the actual function.") actualFunction()
Above code will produce following output:
This is the added text to the actual function. This is the actual function.
In the above code, in line 12 there is a special character @, which mainly indicates that the function which is defined just below it, will be decorated using the
The above code can be interpreted as the following code assume that we don’t have line 12. Then if we want to get the same flavour then we have to override line 17 as following:
actualFunction = sampleDecorator(actualFunction) actualFunction()
Then you will get the same output as before. Observing the above two line what can you assume? We are mainly overwriting the function
actualFunction using the
sampleDecorator function where we are passing the
actualFunction as argument of the decorator function.
Python Decorator Example with single argument
Consider the following code where the function we want to decorate, do have an argument. Notice how we are implementing the decorator python method. Remember the example of flower vase. We will give, the number of flowers that we want to put in.
def flowerDecorator(vasel): def newFlowerVase(n): print("We are decorating the flower vase.") print("You wanted to keep %d flowers in the vase." % n) vasel(n) print("Our decoration is done") return newFlowerVase @flowerDecorator def flowerVase(n): print("We have a flower vase.") flowerVase(6)
Can you assume the output?? The output of the above code will be:
We are decorating the flower vase. You wanted to keep 6 flowers in the vase. We have a flower vase. Our decoration is done
Understanding the python decorator argument code
Now let’s simulate the above code. First in line 18, we call the function
flowerVase(6). Then flow goes to line 13 and sees that this function is being decorated by another function named
flowerDecorator. So it goes to line 1, where the
flowerVase is sent as an argument.
Notice that flowerVase takes a parameter. In the
flowerDecorator function, we are defining a new function named
newFlowerVase that will wrap the actual function and notice this function will have the exactly same number or parameter that the actual function ( flowerVase ) takes.
Then we are adding some new functionalities (printing some message) to it and calling the actual function with parameter which was sent as argument to the
flowerDecorator. And then finally we returned the
newFlowerVase which received by line 18 and we get the output as we decorated it.
This is how a python function decorator work. If your actual function having more than one arguments then the inner function of the decorator will have the same number of parameter.
Python Decorator Example to handle exception
The following code will print the value of an array with respect to its index.
array = ['a', 'b', 'c'] def valueOf(index): print(array[index]) valueOf(0)
This will output:
But what if we call the function for,
This will output:
Traceback (most recent call last): File "D:/T_Code/Pythongenerator/array.py", line 4, in valueOf(10) File "D:/T_Code/Pythongenerator/array.py", line 3, in valueOf print(array[index]) IndexError: list index out of range
As we haven’t handled whether the given index value exceeds the size of the array or not. So now we will decorate this function as following:
array = ['a', 'b', 'c'] def decorator(func): def newValueOf(pos): if pos >= len(array): print("Oops! Array index is out of range") return func(pos) return newValueOf @decorator def valueOf(index): print(array[index]) valueOf(10)
Now it will output as below image.
So now we have handled the possible error of array out of bound exception. That’s all about python decorator example and how it works.