Beginner Level
Intermediate Level
Advanced Level
Introduction
If you've been working with Python for a while, you've probably already encountered decorators - these handy tools that allow you to modify the behavior of functions or classes with minimal code. But did you know that decorators can also take arguments? This powerful feature allows you to create smarter, more versatile decorators that can be customized for different use cases. In this Python tutorial, we'll dive into the world of decorators with arguments, exploring how they work, how to create them, and how to use them to supercharge your Python code.
Table of Contents :
- Decorators with arguments
- Creating decorators with arguments
- Using decorators with arguments
Decorators with arguments :
- Python decorators can also take arguments,
- This can be useful when you want to customize the behavior of a decorator for different use cases.
- To add arguments to a decorator, you need to define a nested function that takes the arguments and returns the actual decorator function.
Creating decorators with arguments
- In the code sample below we'll create a decorator with arguments
- Code Sample :
def greeting_decorator(greeting):
def my_decorator(func):
def wrapper_function(*args, kwargs):
print(greeting)
result = func(*args, kwargs)
return result
return wrapper_function
return my_decorator
Explanation:
- In this example, the
greeting_decorator
is a function that takes agreeting
argument - It returns a decorator function
my_decorator
. - The my_decorator is a nested function that takes a function
func()
as an argument - It returns a wrapped function
wrapper_function
that prints the greeting, calls the original function,
and returns its result.
Using decorators with arguments
- In the code sample below we'll see how we can use the decorator that we created in previous section.
- Code Sample :
@greeting_decorator("Welcome to the party!")
def my_function(name):
print(f"Hello, {name}!")
my_function("Alice")
my_function("Bob")
Output:
Welcome to the party!
Hello, Alice!
Welcome to the party!
Hello, Bob!
Explanation:
- In this example, we use the
greeting_decorator
to create a decorator that displays a custom greeting before calling the decorated function. - We use the
@
symbol to apply thegreeting_decorator
decorator to themy_function
function and pass the "Welcome to the party!" greeting as an argument. - When we call
my_function("Alice")
, the output shows the greeting followed by the function's output with the given name parameter. - Similarly, when we call
my_function("Bob")
, the output shows the greeting followed by the function's output with the given name parameter.
Prev. Tutorial : Decorators
Next Tutorial : Class Decorators