Decorators in python

Decorator, as implied by the term, is akin to a designer who aids with function modification. Given that the decorator doesn’t alter the external layer of function’s structure, it can be regarded to be a modification of that layer. A decorator takes an existing function and adds extra functionality to it without altering the original function. A decorator receives a reference to a function and returns a changed function. The original function is typically called from the updated functions. Because a portion of the program tries to change and enhance functionality in another portion of the program at compile time, this is also known as metaprogramming. It could be challenging to understand the definition, but the video section’s example makes the idea quite clear. The other function is also referred to as a wrapper in Python.

A function that offers a wrap-around for another function is called a wrapper. When utilizing a decorator, the wrapper function is responsible for all of the code that runs both before and after the function that we gave as a parameter. The wrapper function’s goal is to help us. When dealing with several comparable statements, for example, the wrapper can give us some code that is shared by all the functions, and we can use a decorator to call our function in addition to the wrapper. A gathering may receive numerous decorations.

A Python decorator can be created in one of two ways:

We can define a function and provide it to the decorator by passing the function to the decorator as an argument.

Simply place the @ symbol in front of the function you want to embellish.

def inner1(func):

    def inner2():

        print(“Before function execution”);

        func()

        print(“After function execution”)   

    return inner2

@inner1

def function_to_be_used():

    print(“This is inside the function”)

function_to_be_used() 

Output:

Before function execution

This is inside the function

After function execution

The ability to send all the functions to a decorator that needs the same kind of code as the wrapper does has the following advantages: • Decorator functions can make our work more concise.

• We are able to complete our work without making any changes to the function’s original code.

• To a single function, we can apply numerous decorators.

• Python frameworks such as Flask and Django, logging, and execution time measurement all provide decorators for authorization.

Shubhajna Rai
Shubhajna Rai

A Civil Engineering Graduate interested to share valuable information with the aspirants.

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in