Sobes.tech
Junior

What does a decorator return?

sobes.tech AI

Answer from AI

A decorator in Python returns a function (or any other callable object) that replaces the decorated function.

def my_decorator(func):
    def wrapper(*args, **kwargs):
        print("Before calling the function")
        result = func(*args, **kwargs) # Call the original function
        print("After calling the function")
        return result
    return wrapper # The decorator returns the inner function wrapper

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

say_hello()
# Output:
# Before calling the function
# Hello!
# After calling the function

Main points:

  • The decorator takes the decorated function as an argument.
  • Inside the decorator, a new function is defined (usually called wrapper or decorator_func).
  • This new function contains the logic that the decorator adds (before or after calling the original function).
  • The new function calls the original function.
  • The decorator returns this new function.

Thus, when a function is decorated with @decorator_name, the following essentially happens:

def original_function():
    pass

original_function = decorator_name(original_function)

It turns out that the name original_function now refers to the function returned by decorator_name."}]}]}