Decorators are a powerful tool in Python that allow you to modify the behavior of functions or classes. They are often used to add functionality to existing code without changing its structure.

What is a Decorator?

A decorator is a design pattern that allows you to add new functionality to an existing object without modifying its structure. In Python, decorators are used to modify the behavior of functions or methods.

Basic Syntax

def decorator_name(function):
    def wrapper():
        # Code before function
        function()
        # Code after function
    return wrapper

@decorator_name
def my_function():
    print("This is my function")

Types of Decorators

  1. Function Decorators: These are used to modify the behavior of functions.
  2. Class Decorators: These are used to modify the behavior of classes.

Common Use Cases

  • Logging: Decorators can be used to log function calls.
  • Authentication: Decorators can be used to authenticate users before accessing certain functions.
  • Caching: Decorators can be used to cache the results of expensive function calls.

Example: Logging Decorator

def log_decorator(func):
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__} with args: {args} and kwargs: {kwargs}")
        return func(*args, **kwargs)
    return wrapper

@log_decorator
def add(a, b):
    return a + b

result = add(5, 3)
print(result)

Resources

For more information on decorators, check out our Advanced Python Decorators Guide.

Python Decorators