Decorator Function

Mohammad Raisul islam
2 min readOct 27, 2019

This is my very first post in this platform. So hello everyone.

Every programmer needs to modify their code while they are developing. Sometimes I think whether there is any particular solution so that i do not need to change my function rather i can extend the functionality .

Today, I came to know about a tool of python while reading the book “Fluent Python”. It is none other than the decorator function. Without any delay I am sharing my thoughts over the decorator function.

Decorators are mainly used to extend the behaviour of an existing function. Decorators allow us to wrap another function in order to extend the behavior of wrapped function, without permanently modifying it. Following is an example :

Suppose, I’ve a function that divides two numbers .The function will be like following:

Now if some user will provide some input 2,4 instead of 4,2 then it will provide an output (.5). So, it’s my job to make the code efficient enough to provide the output greater than 1.(just a scenario)

There are different logics I can easily apply in the main function. But I don’t want to change my main div function. So, what I will do is just write another function smart_div( ) and make a link between the div( ) and the smart_div( ).

What we have done here is wrote a new function smart_div() and passed a function as an argument there. There is a wrapper function that is actually doing the trick as you guys can see. The wrapper function will take the same number of arguments as the main function does.

In python everything is object .So we are creating a new object div and passed two arguments in the new div object. As we can see, the value didn’t change and we got our expected output.

Another way, we can define the decorator function like the following image:

We do not need to write like “div = smart_div(div)” . Simply, we can just write “@smart_div” before our main div function .

Happy coding

--

--