Python

How to use Python Decorators

In this article, we will see how to use Python Decorators.

1. Introduction

python decorators

Python is an easy-to-learn, powerful programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. Python’s elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas on most platforms.

A decorator is a function that takes in a function, adds some functionality to it, and returns the original function.

2. Example

In this section, we will see a working example of decorators.

2.1 Function as an argument

Let us create a function that takes name as a parameter and returns ‘Hello <name>‘ where name is the value of the parameter when this function is called.

def hello(name):
    return 'Hello ' + name

Now let us create another function greeting. This function will take two parameters. The first parameter is a function and the second one is a String. This new function will call the function which is passed as a parameter and the second parameter will be passed as the argument to the function as below:

def greeting(func, name):
    return func(name) + ', How are you'

Now let us print the result:

print(greeting(hello, 'Java devs'))

Below is the full source code:

def hello(name):
    return 'Hello ' + name

def greeting(func, name):
    return func(name) + ', How are you'

print(greeting(hello, 'Java devs'))

When you will execute the above code the output will be Hello Java devs, How are you

2.2 Function inside a function

In this section, we will see how we can define a function inside another function. Let us first show you the code:

def outerFunc(name):
    greeting = 'Hello'
    
    def innerFunc():
        print(greeting, name)
        
    innerFunc()
    
outerFunc('JCG')

We define a function names outerFunc which takes a name as a parameter. We declare a variable greeting and assign value Hello to it. Now we defined another function innerFunc inside the outerFunc. This function will print the greeting with the name. then we call this innerFunc. The above code will print ‘Hello JCG’

In Python, a function can also return another function. Let us change the above code a little bit as below:

def outerFunc(name):
    greeting = 'Hello'
    
    def innerFunc():
        print(greeting, name)
        
    return innerFunc
    
func = outerFunc('I love Python')
func()

Did you see the change? On line 7 we are now returning the function return innerFunc (Note that the parenthesis after the function name has been removed). Then we call this outerFunc on line 9 which return us the innerFunc. We assign this to a variable func.

2.3 Decorator function

In this section, we will see how a decorator function works in Python using an example. Let us first define a simple function that prints ‘Hello Coders’

def hello():
    print("Hello Coders")

Now let us define a decorator function that takes another function as an argument:

def hello():
    print("Hello Coders")
    
def display(func):
    
    def innerFunc():
        print("Running", func.__name__, "function")
        func()
        print(func.__name__, "funtion stopped")
    return innerFunc

decorated_func = display(hello)
decorated_func()

In the above code, we create a simple hello function that just prints ‘Hello Coders’. Then we create a new function called display which takes another function as an argument and returns an inner function. The inner function first prints ‘Running <function-name> function’, then it calls the function which is passed in the argument. In our case, this will call the hello function. At the end it will print ‘<function_name> function stopped‘ . We call the display function passing the hello function and store the result in the variable decorated_func. We then call decorated_func()

When you execute the above code you will see the below result:

Running hello function
Hello Coders
hello funtion stopped

3. Summary

The decorated function acts as a wrapper by allowing us to add functionality to the function passed in the parameter without changing the code of the original function. In Python, you can pass a function as an argument and can also define a function inside a function.

In this article, we saw how to achieve it. We also looked at an example of a decorator function where the function behavior was changed at runtime. This is a very handy feature and many programming languages make use of it in its own way.

Mohammad Meraj Zia

Senior Java Developer
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button