Ever since I started working on Django framework, one thing that perplexed me was ‘decorators’. They are generally applied before method definition and also on the classes. In this article we shall be focusing on ‘method based decorators’.

Fist let us understand some function related concepts.

Functions are first-class objects. This means that functions can be passed around, and used as arguments, just like any other value (e.g, string, int, float). Decorator uses this same feature to add more value to your function.

A decorator wraps your function and adds some of its own functionality before and after your function execution.

Let us see an example


my_function is a normal function. For wrapping it we define my_decorator()

which takes my_function or any other function as an argument. my_decorator() has an inner function wrapper() this is the core function which wraps additional functionality around our function. The output of the above code would be as follow,

To accommodate function which takes an argument we add two parameters in the wrapper function

Adding syntactic sugar ‘@’

Instead of wrapping the function as mentioned in the last two lines above you can also use the ‘@’ for decorating a function as follow

But sometimes you need a decorator itself to take an argument, below is the code for such case

Output

Click here for more details…


At BoTree Technologies, we build enterprise applications with our Python team of 15+ engineers.

We also specialize in RPA, AI, Django, JavaScript and ReactJS.

Consulting is free – let us help you grow!