What Is Decorator In Python With Example

Decorators can add new functions or restrictions to the decorated objects without modifying the original source code. There are many kinds of decorators, including function decorators and class decorators. The name of decorator is different in many programming languages. It embodies the decoration pattern in the design pattern and emphasizes the open and closed principle.

The syntax of decorator is to put @decorator_name on the decorated object.

@decorator_name
def func():
    pass

Python programs are executed in order from top to bottom. When a block of code that defines a function is encountered, it is not executed immediately, it is executed only when the function is called somewhere in python source code.

Because of sequential execution, if you really define the same name function twice, the later definition will overwrite the previous one. Therefore, there are differences in the placement of code in python, which cannot be placed at will. Usually, the function body should be placed before the function call statement.

1. Python Decorator Example.

>>> def auth_decorator(func):
...     def auth():
...         
...         print("Auth success.")
...         
...         result = func()
...         
...         print("Function execute complete.")
...         
...         return result
...     # return auth function.
...     return auth
... 
>>> @auth_decorator
... def func_1():
...     print("func_1 is running.")
... 
>>> func_1
<function auth_decorator.<locals>.auth at 0x10e8d58c0>
>>> 
>>> 
>>> func_1()
Auth success.

func_1 is running.

Function execute complete.

>>> @auth_decorator
... def func_2():
...     print("func_2 is running.")
... 
>>> func_2()
Auth success.

func_2 is running.

Function execute complete.

In this example, i do following.

  1. Define a decorator function auth_decorator.
  2. The auth_decorator function has a func input parameter, this parameter is the function name which this decorator decorated.
  3. Define an inner function in auth_decorator function, the inner function name is auth, it will invoke the input decorated function func in the inner function. And the auth function will be returned by the auth_decorator function.
  4. Use @auth_decorator to decorate function func_1.
  5. So when you invoke function func_1, it will first pass function func_1 to the decorator function ( auth_decorator ) as parameter. The decorator return the inner auth function, so the auth function will be executed.
  6. In the auth function, it will first print out “Auth success.” message, then it will execute the input function( func_1 ) and return the func_1 function’s output. Then it will print out “Function execute complete.” message.
  7. Now you can use the function decorator @auth_decorator to add authentication feature to another function func_2.

2. Pass Function Parameter To Decorator Function.

2.1 Pass Two Function Parameters.

>>> def auth_decorator(func):
...     def auth(username, password):
...         
...         print("Auth success for user ", username, ", ", password)
...         
...         result = func(username, password)
...         
...         print("Function execute complete.")
...         
...         return result
...     
...     return auth
... 
>>> @auth_decorator
... def func_2(username, password):
...     
...     print("Hello ", username, ", your password is ", password)
... 
>>> func_2('tom', '123456')
Auth success for user  tom ,  123456

Hello  tom , your password is  123456

Function execute complete.

2.2 Pass Multiple Number And Type Parameters.

>>> def auth_decorator(func):
...     def auth(*args, **kwargs):

...             for arg in args:
...                     print(arg)

...             for key in kwargs:
...                     value = kwargs[key]
...                     print(key, value)

...             result = func(*args, **kwargs)

...             print("Function execute complete.")

...             return result

...     return auth
... 
>>> @auth_decorator
... def func_2(username, password):
...     
...     print("Hello ", username, ", your password is ", password)
... 
>>> 
>>> func_2('tom', '123456')

tom

123456

Hello  tom , your password is  123456

Function execute complete.

3. Decorate Function With Multiple Function Decorator.

We can add multiple function decorator to one python function, below is an example.

def dec_1(func):

    def dec_1_execute(*args, **kwargs):

        print("Decorator_1 is running. ")

        result = func(*args, **kwargs)

        print("Decorator_1 execute complete.")

        return result

    return dec_1_execute

def dec_2(func):

    def dec_2_execute(*args, **kwargs):

        print("Decorator_2 is running. ")

        result = func(*args, **kwargs)

        print("Decorator_2 execute complete.")

        return result

    return dec_2_execute
    
@dec_1
@dec_2
def func_2(username, password):
    
    print("Hello ", username, ", your password is ", password)

if __name__ == '__main__':
    
    func_2('tom', '123456')

Below is above code output. We can see that the two function decorator will be executed in order. Then the function func_2 will be executed. After that the two decorator will be exit in reserved order.

Decorator_1 is running. 
Decorator_2 is running. 

Hello  tom , your password is  123456

Decorator_2 execute complete.

Decorator_1 execute complete.

Leave a Comment

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

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