Interview Questions

How Python Decorators Actually Work (With Step-by-Step Code Examples)

Author: Interview Questions Posted 14 days ago 24 min read

What is a decorator in Python?

A decorator is a design pattern that allows you to modify or extend the behavior of a function or class without permanently modifying its source code. In Python, functions are first-class objects, meaning they can be passed as arguments and returned from other functions.

def my_decorator(func):
    def wrapper():
        print("Something happens before the function.")
        func()
        print("Something happens after the function.")
    return wrapper

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

say_hello()

Deep Dive: What say_hello Really Becomes Under the Hood

To truly master decorators, it helps to demystify the @ syntactic sugar.

When you write:

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

Python is simply performing a neat shortcut. This syntax is 100% equivalent to writing:

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

# The decorator wraps the original function and rebinds the name
say_hello = my_decorator(say_hello)

Why Returning wrapper Makes This Work

  1. The Function Reassignment: When Python evaluates say_hello = my_decorator(say_hello), it passes your original say_hello function into my_decorator as the func argument.
  2. Returning the Wrapper: Inside my_decorator, the inner function wrapper is created and returned using return wrapper. Notice there are no parentheses after wrapper—we are returning the function object itself, not calling it yet.
  3. Variable Rebinding: Because say_hello is assigned the result of my_decorator(say_hello), the variable name say_hello now points directly to the wrapper function, not the original say_hello function.
  4. Execution: Later, when you call say_hello(), you aren't calling your original function anymore—you are executing wrapper(). Inside wrapper, it runs the pre-code, invokes the original function (using the func reference it remembers through closure), and runs the post-code.

A Quick Demonstration:

If you check the __name__ of your decorated function without using functools.wraps, you can see this redirection in action:

print(say_hello.__name__)  # Output: wrapper (because say_hello now points to the wrapper function!)

(Tip for production code: Always use @functools.wraps(func) on your wrapper function to preserve the original function's metadata, docstrings, and name!)

Handling Function Parameters in Decorators (*args and **kwargs)

What happens when your target function needs to accept parameters—like greeting a specific user by name?

If your decorator's wrapper function doesn't accept arguments, calling say_hello("Alice") will immediately crash with a TypeError: wrapper() takes 0 positional arguments but 1 was given.

To make decorators flexible enough to handle any function signature, the wrapper must accept *args and **kwargs and pass them along to the original function.

The Complete Example

def my_decorator(func):
    # wrapper now accepts *args and **kwargs to handle any input parameters
    def wrapper(*args, **kwargs):
        print(f"--- Log: About to run '{func.__name__}' ---")

        # Execute the original function, forwarding all arguments
        result = func(*args, **kwargs)

        print(f"--- Log: Finished running '{func.__name__}' ---")
        return result  # Return the original function's return value (if any)

    return wrapper

@my_decorator
def say_hello(name):
    print(f"Hello, {name}!")

# Under the hood, Python still performs this exact rebinding:
# say_hello = my_decorator(say_hello)

# Calling the decorated function
say_hello("Alice")

What Happens Behind the Scenes Now?

  1. The Rebinding: When Python evaluates @my_decorator, it runs say_hello = my_decorator(say_hello). The variable say_hello now points to the wrapper function.
  2. Passing the Argument: When you call say_hello("Alice"), you are actually calling wrapper("Alice").
  3. Catching and Forwarding:
  4. wrapper catches "Alice" inside its *args tuple.
  5. Inside wrapper, it executes func(*args, **kwargs), which unpacks and passes "Alice" down to your original say_hello function.

  6. Execution Output:

--- Log: About to run 'say_hello' ---
Hello, Alice!
--- Log: Finished running 'say_hello' ---

Using *args and **kwargs inside your wrapper ensures your decorator remains universal—meaning you can slap it onto a function with zero parameters, one parameter, or ten keyword parameters, and it will never break!