Python Decorators

  • By
  • September 3, 2022
  • Python
Python Decorator

Python Decorators

A decorator means it takes functions first then add some extra functionality to the program and returns it.

Python has interesting features called as decorators to add functionality to existing code.

This concept is called metaprogramming because a part of the program tries to modify another part of the program while compiling time.

To understand the concept of decorators we must know a few things about python. We must be comfortable with the fact that in python everything is an object. The names that we define are simply identifiers bound to objects. Functions are not exceptions they are objects too with attributes. For the same function, objects can be bound to different names. The Python Training in Pune at  SevenMentor’s leads our trainees from the fundamental concepts of writing and executing scripts of python

Here is an example.

def first(msg):

    print(msg)

first(“Hello”)

second = first

second(“Hello”)

Output

Hello

Hello

When you run this code, you will get the same output for the first and second functions. Here the names first and second refer to the first functions object.

Functions can be passed as arguments to another function in decorators.

If you use map, filter, and reduce with the help of functions in python then you already know about this. It means these type of functions that takes other functions as arguments are also called order higher functions.

SevenMentor is not only the Best Python Course in Pune for students but also student develops their technical skills and places them in good IT companies.

 

For Free, Demo classes Call: 02071171500

Registration Link: Click Here!

 

Here is an example of such a function which shows like function is working as arguments:

def inc(x):

    return x + 1

def dec(x):

    return x – 1

def operate(func, x):

    result = func(x)

    return result

We invoke the function as follows.

>>> operate(inc,3)

4

>>> operate(dec,3)

2

Furthermore, a function can return another function.

def is_called():

    def is_returned():

        print(“Hello”)

    return is_returned

new = is_called()

# Outputs “Hello”

new()

Output

Hello

 

Here in the above program is_returned() is working as a nested function which is defined and returned each time when we call the function is_call(). Here we can conclude that with this concept we know the things regarding closures in python. 

 

For Free, Demo classes Call: 02071171500

Registration Link: Click Here!

 

 

Methods and functions are called callable as they can be called when required.

In this fact any object which implements a special method called __call__() method this method is called callable. Here we can say that a decorator is callable when we need to call .

def make_pretty(func):

    def inner():

        print(“I got decorated”)

        func()

    return inner

def ordinary():

    print(“I am ordinary”)

when you run this program on the interpreter

>>> ordinary()

I am ordinary

>>> # let’s decorate this ordinary function

>>> pretty = make_pretty(ordinary)

>>> pretty()

I got decorated

I am ordinary

In the example shown above, make_pretty() is a decorator. In the assignment step:

pretty = make_pretty(ordinary)

here in the program ordinary() is decorated and its return function was given the pretty name. 

we can see the decorators are adding new functionality to the already available function. This method is similar to wrapping data as a gift.  we can say that decorators act as wrappers.

Generally what we do in decorators is reassign the function as 

ordinary = make_pretty(ordinary).

Python has a syntax to simplify this common construct for a reason.

 

For Free, Demo classes Call: 02071171500

Registration Link: Click Here!

 

 

When we use function as a decorator to identify that function we apply @ symbol in our program

For example :

@make_pretty

def ordinary():

    print(“I am ordinary”)

is equivalent to

def ordinary():

    print(“I am ordinary”)

ordinary = make_pretty(ordinary)

with parameters decorating function

as we see in the above program all the functions are defined without parameters. so now we are using parameters also 

def divide(a, b):

    return a/b

As shown in the above program, we passed two parameters a and b. If we pass the value to 0, it will go through an error.

>>> divide(2,5)

0.4

>>> divide(2,0)

Traceback (most recent call last):

ZeroDivisionError: division by zero

Now we will check how it causes an error 

def smart_divide(func):

    def inner(p,q):

        print(“I am dividing these two”, p, “and”, q)

        if q == 0:

            print(“Whoops! cannot divide”)

            return

        return func(p,q)

    return inner

@smart_divide

def divide(p,q):

    print(p,q)

This new type will return None if the error condition arises while running the program.

>>> divide(2,5)

I am dividing these two 2 and 5

0.4

>>> divide(2,0)

I am dividing these two 2 and 0

Whoops! cannot divide

With help of this, we can decorate functions that take parameters.

Here the decorator’s concept is done.

 

Author:-

Sneha Ranbhidkar
Call the Trainer and Book your free demo Class 

Call now!!! | SevenMentor Pvt Ltd.

© Copyright 2021 | Sevenmentor Pvt Ltd.

Submit Comment

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

*
*