Getting started: Python Decorators

This post will help you get started with Python decorators through some real life examples. Some familiarity with the Python programming language is expected.

 

Before directly jumping into decorators, let’s take a step back and start with Python functions. This will help you understand the concepts better.

Functions

A function in Python can be defined as follows:

This function takes name as input and returns a string, where:

  • def is the keyword used to define a function.
  • introduce is the name of the function.
  • the variable inside parentheses (name) is the required argument for the function.
  • next line is the body or definition of the function.

Function Properties

In Python, functions are treated as first-class objects. This means that Python treats functions as values. We can assign a function to a variable, pass it as an argument to another function, or return it as a value from another function.

We have defined a function 'print_hello_world’. Now we can assign it to a variable.

(Here >>> is denoting the python interactive shell)

Now we can call modified_world just like the function print_hello_world.

We can also pass a function to another function as an argument.

So now when we pass print_hello_world function to execute function, the output will be as follows:

Python also supports the nesting of functions. It means we can define another function in the body or definition of some other function. Example:

In the example above, we have used two concepts described earlier.

1. Returning a function (bar) as a return value of the function foo

2. Nesting function bar in the definition of the function foo

Let’s see this code in action.

Here v1 stores the return value of the function foo,which is another function bar. Now what will happen if we call v1 with some parameter?

When a function is handled as data (in our case, return as a value from another function), it implicitly carries information required to execute the function. This is called closures in Python. We can check the closure of the function using __closure__ attribute of the function. This will return a tuple containing all the closures of the function. If we want to see any content of the closure, we can do something like v1.__closure__[0].cell_contents.

So, now that we looked at both function properties, let's see how we can use these properties in real scenarios.

Going Ahead

Suppose we want to perform some generic functionality before or/and after function execution. It can be like printing the execution time of the function.

One way to do this is by writing whatever we want to do before and after execution as initial and final statements, respectively. Example:

Is this a good way. I leave it to you. What will happen if we have several functions and need to perform the same task for all other functions too?

Another way could be to write a function that will take any other function as an argument and return the function along with performing the task before and after function execution. Example:

The function print_hello_world just prints ‘Hello World’. Function dec takes a function as an argument and creates another function nest_func in its definition. nest_func prints some statements before and after the execution of the function is passed as an argument to function dec.

Let’s pass the function print_hello_world to dec.

new_print_function is another function returned by the function dec. What will be the output on calling new_print_hello_world function? Let’s check it.

What if we assign the new function returned by the dec function to print_hello_world function again?

Let’s call print_hello_world function now.

We have changed the functionality of the function print_hello_world without changing the source code of the function itself.

So what next? If everything is clear till this point, then we have already learned about decorators. Let me explain.

Decorators

A decorator is a function which gives us the freedom to enhance or change the functionality of any function dynamically, without making changes in the code of the function.

In our case, function dec provides us with this functionality (as it changes the functionality of the function print_hello_world). So dec is called decorator. Instead of passing print_hello_world explicitly to function dec, we can use its shorthand syntax:

I hope by now you understand what decorators are. You might be wondering why we need to return a function from the dec function? Just call the function in dec itself in which we can print statements along with executing the function passed as an argument. Example:

I have a few questions for you in answer. Suppose, I agree with you and decide to do it as suggested.

  1. What value does print_hello_world store right now? Can you call it now? (It is storing None which is the return value of the function dec1. So you can’t call print_hello_world now)
  2. What if we want to enhance a function having some arguments? One suggestion could be like this:

But the problem is this: how do you get the value of arg1 and arg2 at the time of passing any function to dec2?

Here, we will not be able to get the value of arg1 and arg2.

I hope these two points clearly explain why decorators are required to return a function.

Decorator Examples

  • It can be used to compute the execution time of any function.
  • In web applications, it can be used to check if the user is logged in or not.

I hope this article gives you a basic idea about Python decorators and some of their use cases. If you have any queries or feedback, you can reach me at udr.ritesh@gmail.com.

About the Author

Ritesh Agrawal
Software Engineer @HackerEarth. Mostly I code in python. I like to explore new technologies, tools. etc. Software development is my work as well as my hobby.

Author Post

Share