Moving on from the last topic of functions, let’s perform another task. I want to write a function of dividing two numbers. It’s a simple task.

It’s working well. Now I want the denominator to be zero.

OK, an error as expected because you can’t divide anything by zero. Now my boss wants me to do something so that this error doesn’t occur. Instead a message or something is displayed that You can’t divide by zero. Again this is easy. But here is a catch. My boss doesn’t want to do any changes in the existing function. Absolutely no modification is allowed. Then, what can I do? Let’s use our concepts of calling functions as arguments and all that we have studied till now.
I am making another function and let me call it check_div_op and let the variable func is it’s parameter. Now make a nested function. It’s inside it so name it inner. The parameter of this function is the same as of our original function, a, b. In this inner function we will perform our checking operation. If b is equal to zero, then print some message. We will return this to func with parameters a, b. And then we will return the inner function. Finally, we will pass our main function div_op as an argument to the outer nested function check_div_out and assign it back to our main function. Then, print the result. Let’s see the code.

If the second number is zero, it will go inside the nested function, check the condition, print the message, return the printed result to the outer function and this function will be assigned as a result to the main function. What have we achieved? We didn’t modify our original function. When there is a function which can add additional functionality to the original function without modifying the original function, that function is called Decorator Function. Here check_div_op () is a decorator function. You can assign a decorator function to the main function by simply writing @name of the decorator function just above the main function. In that case, there is no need to perform the assigning operation of the main function as a parameter to the decorator function and then assigning it back to the main function.

Do remember that there is no need for a decorator function unless you don’t want to tamper with your main function. Now this is a very small function. You can modify the function here as follows.

Two lines and job done. But, what if you have written 100 lines of code which only you and GOD knows what it’s doing and fortunately it’s working correctly also. And someone says to slightly modify it to check something. Believe me; you’ll love to write a decorator function.
