5.1 Introduction to Decorators
Decorators are functions that take another function as an argument and return a new function, altering or extending the behavior of the original function. Decorators are used to improve code readability and reusability.
Decorators allow you to modify the behavior of functions or methods without changing their source code. Thus, they are widely used to add functionality, logging, access control, and many other tasks.
The syntax for decorators in Python involves using the @ symbol before the name of the decorator, which is placed before the function definition.
@decorator
def my_function():
pass
This is equivalent to the following code:
def my_function():
pass
my_function = decorator(my_function)
Think carefully about what's happening here: we declare the function
my_function
, but then replace it with the function decorator
, with our function passed as a parameter. The function
decorator
can call our function at its discretion.
5.2 Creating a Simple Decorator
Let's look at a simple decorator that outputs a message before and after the function call.
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()
Explanation
Decorator (my_decorator)
: This function takes the function func
as an argument and returns a new function wrapper
that calls func
and adds additional behavior before and after its call.
Function with Decorator (say_hello)
: The function say_hello
is wrapped with the decorator my_decorator
, adding additional behavior when it is called.
Output:
# Before calling the function
Hello!
# After calling the function
5.3 Decorators with Arguments
Decorators can take arguments, allowing you to flexibly adjust their behavior.
def repeat(num_times):
def decorator_repeat(func):
def wrapper(*args, **kwargs):
for _ in range(num_times):
func(*args, **kwargs)
return wrapper
return decorator_repeat
@repeat(num_times=3)
def say_hello(name):
print(f"Hello, {name}!")
say_hello("Alice")
Explanation
Decorator with Arguments (repeat)
: This function takes the argument num_times
and returns the decorator decorator_repeat
.
Decorator (decorator_repeat)
: This decorator takes the function func
and returns a new function wrapper
that calls func
num_times
times.
Function with Decorator (say_hello)
: The function say_hello
is called three times thanks to the decorator repeat
.
Output:
Hello, Alice!
Hello, Alice!
Hello, Alice!
GO TO FULL VERSION