Course Content
Mastering Python: Closures and Decorators
Mastering Python: Closures and Decorators
Decorator with Parameters
There are situations where decorators need to take parameters to modify their behavior. For instance, in the previous Task, you implemented the int_validate()
decorator to validate integer inputs, but what if you need to validate other data types as well?
In such cases, you can modify the decorator to accept parameters that specify the data type to validate. But before that, let's first understand how parameters work in decorators.
Implementation
To use parameters in a decorator, you need to create an additional layer of non-local scope.
Ordinary Decorator | Decorator with Parameters |
First outer function (for parameter closure) | |
Outer function (for function closure). | Second outer function (for function closure). |
Inner function (function wrapper). | Inner function (function wrapper). |
Let's take a look at an example:
def decorator(param1, param2): def inner(func): def wrapper(*args): print("Parameters:", param1, param2) return func(*args) return wrapper return inner @decorator("First", "Second") def add(a, b): return a + b print(add(25, 13))
In the example above, the decorator()
function takes two parameters (param1
and param2
) and returns the inner()
function with enclosed parameters. After, the inner() function is used as an ordinary decorator.
Note
The
decorator()
function returns theinner() function, enclosing the parameters in it. The returned
inner()` function becomes a new decorator with closed parameters and is then applied to the function you need to be decorated.
How it works in code:
Steps for applying decorators
Step | Ordinary Decorator | Decorator with Parameters |
1 | add = decorator(add) | add = decorator(param1, param2)(add) |
2 | add = wrapper | add = inner(add) |
3 | add = wrapper |
Note
The second parentheses
()
are the call of the returned object.
Thanks for your feedback!