In this lesson, you will learn how to create simple wrapper functions that intercept calls to other functions to execute code before or after their primary logic.
At their core, decorators are a clean, readable way to modify the behavior of a function without changing its internal source code. Because functions in Python are "first-class objects," you can pass them as arguments to other functions. A decorator is simply a function that takes another function as an input, wraps it in a new "inner" function, and returns that inner function to replace the original.
How it Works
Think of a decorator like a gift wrapper. The original function is the gift, and the decorator adds extra layers (like logging or timing) before and after the recipient opens it.
Here is how you build a basic decorator:
def my_decorator(func):
def wrapper():
print("Before the function runs!")
func()
print("After the function runs!")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
# Now, calling say_hello() triggers the wrapper
say_hello()
When you use the @my_decorator syntax above a function definition, Python automatically passes say_hello into my_decorator. The variable say_hello is then reassigned to the wrapper function returned by the decorator.
When you call say_hello(), you are actually executing the wrapper function. It executes your "before" code, calls the original func() (the original say_hello), and then executes your "after" code.
This pattern is incredibly powerful for cross-cutting concerns—tasks that need to happen across many different functions, such as logging performance, checking user permissions, or tracking how many times a function is invoked. By keeping this logic inside a decorator, your primary functions stay focused on their specific, single responsibility, while the "infrastructure" code is handled transparently in the background.
Key Takeaway: A decorator is a function that accepts another function, wraps it inside an inner function to add extra behavior, and returns that wrapper to execute in place of the original.