Understanding decorators in Python

Augustine Alul - Sep 8 - - Dev Community

Introduction:
Have you ever come across a Python code base where "@login_required" or where the "@" sign is used with any other suffix on top of a function or class and you immediately begin to wonder what it is or what is its purpose?

Or have you in the past used a framework where the documentation says you should use a certain decorator to achieve a particular functionality but you just do not know how the implementation is done under the hood and would love to find out?

Or maybe, it is understandable that you are new to the concept of decorators and would love to learn about it, hang in there, you are well on track to do so.

Prerequisites:
For maximum understanding of the concepts in this tutorial, it is necessary to have a background knowledge of Python programming.

What are decorators:
Decorators are used in Python to give extra functionality to classes, and functions without altering the initial code structure of the class or function as the case may be. Decorators are sometimes referred to as "syntactic sugar", as they tend to improve the behavior of a class or function.

If you are caught up in a situation whereby you have a function of class bundled up with certain functionalities that are already in use by a larger part of your program or software, as the case may be, and you want the class/function to have a slight modification for an intended use within the program, and at the same time u don't want to break the functioning of the existing codebase because of how tightly coupled it is, what do you think is the best approach in this situation?
You guessed right, all you simply need to do is decorate the class/function to achieve the desired functionality without breaking the existing program where they are being used.
Just like it was stated in the introductory part of this tutorial where "@login_required" was used to cite an instance, it is indeed a decorator used in the Flask framework, which happens to be a popular backend framework, whenever the "@login_required" decorator is placed on top of a view function, it causes access to the view function to be restricted to just the users that have been authenticated/logged in to the application. Here again, we see the real-world application of decorators and how it can be utilized in building software.

From a technical perspective and a lower level, decorators are functions that take other functions or classes as arguments and then wrap them in a wrapper function that extends/modifies their functionality, then the decorator function now returns the outcome of the modification done by the wrapper function.

Here are some code snippets for aid clarification and better understanding;

def hello():
    print("Hello readers")
Enter fullscreen mode Exit fullscreen mode

hello() is a function that has been defined to display "Hello readers" whenever it is being called, and it might already be in use in a larger part of my program.

And now I need to modify the display message from the hello function without defining a new function explicitly in my program, I can apply decoration on the hello() function to achieve the desired modified outcome by simply using a decorator.

The first step is to define your decorator function

 def decorator(func):
    def wrapper():
        print("in the decorated function")
        func()
        print("bye, leaving the decorated function")
    return wrapper
Enter fullscreen mode Exit fullscreen mode

The second step and last step is to place the decorator function as a suffix to the "@" sign on top of the function to be decorated.

@decorator
def hello():
    print("Hello readers")

# Calling the decorated function
hello()

This outputs:

        in the decorated function
        Hello readers
        bye, leaving the decorated  function
Enter fullscreen mode Exit fullscreen mode

In summary, decorators in python modify the behavior of functions and classes without altering the structure of the already defined code, thereby improving certain behaviors of the class or function, as the case may be.

Thanks for reading.

Happy coding...

. .
Terabox Video Player