Decorating Python Functions with Decorators

Decorating the python function to change the behavior of the function.

Decorating Python Functions with Decorators

Understating decorator is much more simplified when you have the concept of closure. But even before closure we need to know that python function are first class member. To say that functions are first class member in python means that they can be manipulated like other kinds of objects i.e. :

  1. Functions can be passed inside a function.
  2. Functions can be returned from a function.
  3. Function can be assigned to a variable.

Decorators are built upon these three pillars. Now let us know about closure with an example:

s1.jpg

r1.jpeg

What you see here is variable 'a' in accessible to the inner function as well which means the inner function encloses the variable 'a' and hence known as closure. This kind of variables are called non-local variables. When 'foo' method returns a 'bar' method, python attach any non local variables, that 'bar' needs to the function object. So if we pass any variable in outer function that variable can be accessed from the inner function.

Now finally we are ready to understand how can we decorate the python function. These decorators are generally used to modify the behavior of functions.

Imagine we have a function and we would like to calculate the time required to execute that function. (For now do not concern about time.sleep)

s2.jpg

Now lets create a decorator function that calculates the time required to execute two functions. For that we create a wrapper function inside a function which calculates time to execute any functions passed.

image_2022-09-19_002133256.png

Now we need to call the timer function. It is done in particular way: name_of_the_function = decorator_func(name_of_the_function) name_of_the_function() i.e. image_2022-09-19_003612041.png

ra.jpg

This is equivalent to doing: f-q.jpg

f-r.jpg

This notion of changing the behavior of functions as we want can be done by the art of decorators. This helps to utilize one of the python's important aspect DRY(Don't repeat yourself).

By the way there is something for you to check, which which list creation method is faster? Is it l=[] or l= List()? And why is it so? Keep in mind there is delay of 0.01 in program!