python
  1. python-decorators

Python Decorators

Python decorators are functions that enable us to modify other functions, classes, or methods without modifying their source code. They provide a simple syntax for calling higher-order functions.

Syntax

@decorator_function
def original_function():
    # function body

Example

def decorator_function(original_function):
    def wrapper_function():
        print('Wrapper function executed before the original function')
        original_function()
        print('Wrapper function executed after the original function')
        
    return wrapper_function

@decorator_function
def hello_world():
    print('Hello, World!')

hello_world()

Output

Wrapper function executed before the original function
Hello, World!
Wrapper function executed after the original function

Explanation

The decorator_function is defined, which takes the original_function as an argument. It defines a new function wrapper_function that prints a message before and after calling the original_function.

When hello_world is called, it is decorated by passing it as an argument to the decorator_function using the @ symbol. The decorator returns the wrapper_function, which is then called when hello_world is executed.

The wrapper_function calls the original_function, which in this case, prints 'Hello, World!'. The messages before and after calling the original_function are printed by the wrapper_function.

Use

Python decorators can be used to modify the behavior of functions, methods, or classes without modifying the original source code. They can be used for tasks such as logging, timing, memoization, and authentication.

Important Points

  • Decorators use the @ symbol to modify functions, methods, or classes.
  • Decorator functions can take the original function as an argument and return a new function.
  • The new function can modify the original function's behavior before and/or after it is called.

Summary

Python decorators allow us to modify the behavior of functions, methods, or classes without modifying their source code. They use the @ symbol to apply a decorator function, which can modify the original function's behavior before and/or after it is called. Decorators can be used for a variety of tasks such as logging, timing, memoization, and authentication.

Published on: