What is function decorators in Python?

Background

Following are important facts about functions in Python that are useful to understand decorator functions.

In Python, we can define a function inside another function.

In Python, a function can be passed as parameter to another function (a function can also return another function).

In Python, a decorator is a special type of function that can be used to modify or extend the behavior of another function without changing its source code. Decorators can be used to add functionality to a function, such as logging, caching, or input validation, or to modify the behavior of a function, such as by adding memoization or implementing a retry mechanism.

A decorator is essentially a wrapper function that takes in a function as its input, performs some operation on that function, and returns the modified function. The syntax for applying a decorator to a function is to place the decorator function above the function definition, using the '@' symbol followed by the decorator function's name.

Here's an example of a simple decorator that adds logging functionality to a function: 

 

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

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

result = add(2, 3)

In this example, the 'log' function is a decorator that takes in another function as its input and returns a wrapper function that logs the name of the function being called, as well as its arguments and keyword arguments, before calling the original function. The '@log' syntax is then used to apply the decorator to the 'add' function, which adds two numbers together.

When the 'add' function is called with arguments (2, 3), the output will be: 

 

Calling function add with args (2, 3) and kwargs {}
5

This demonstrates how a decorator can be used to add additional functionality to a function without modifying its source code.

Submit Your Programming Assignment Details