How do you create a decorator in Python?

Understanding Python Decorators

The correct answer to the question "How do you create a decorator in Python?" is: "By defining a function that takes another function as an argument". This means a decorator in Python is simply a callable Python object used to modify a function or a class.

A Python decorator takes another function as an argument, and extends the behavior of this function without explicitly modifying it. Here's a simple example of how to create and use a decorator:

def my_decorator(func):
    def wrapper():
        print("Before calling the function")
        func()
        print("After calling the function")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()

In this example, my_decorator is a function that takes another function (say_hello in this case) as its argument. The @my_decorator syntax is just an easier way of saying say_hello = my_decorator(say_hello). It's called syntactic sugar - it makes the behavior of modifying say_hello with my_decorator easier to understand and read.

Now, let's run say_hello:

Before calling the function
Hello!
After calling the function

As its output shows, before calling the actual say_hello function, the code in the wrapper function was executed first.

It's important to note that although the @decorator syntax does make it easier to implement decorators, it is not strictly necessary for creating decorators. As shown in the quiz answer and the example provided, the defining feature of decorators is that they are functions that take other functions as their arguments. They can then provide additional functionality to these functions or alter their behavior in some way, all without changing the source code of the function being decorated.

Do you find this helpful?