How to make a decorator in Python

"Learn how to make a Python decorator with an example and use it to improve your code's readability and performance!"

Making a Decorator in Python

Python is a great language for creating decorators, which are great for adding custom behavior to existing functions. Decorators are used to modify existing functions and can be used to add additional functionality, logging, or other custom behavior. Here is an example of a simple decorator that adds logging to a function:

def log_function(func):
    def wrapper(*args, **kwargs):
        print(f'Calling {func.__name__} with args: {args}, kwargs: {kwargs}')
        return func(*args, **kwargs)
    return wrapper

@log_function
def add(x, y):
    return x + y

print(add(3, 4))

When the above code is run, it prints the following output:

Calling add with args: (3, 4), kwargs: {}
7

The @log_function decorator above is applied to the add() function. This means that whenever the add() function is called, the log_function() decorator is called first. The log_function() decorator prints out the arguments that were passed to the add() function before calling the add() function itself. Decorators are a great way to add custom behavior to existing functions in Python.

Answers (0)