Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Decorator with Parameters | Decorators
Mastering Python: Closures and Decorators
course content

Зміст курсу

Mastering Python: Closures and Decorators

Mastering Python: Closures and Decorators

1. Scopes
2. Closure
3. Decorators

bookDecorator 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 DecoratorDecorator 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:

1234567891011121314
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))
copy

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 the inner() 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

StepOrdinary DecoratorDecorator with Parameters
1add = decorator(add)add = decorator(param1, param2)(add)
2add = wrapperadd = inner(add)
3add = wrapper

Note

The second parentheses () are the call of the returned object.

1. How many functions do you need to define a ordinary decorator?
2. How many functions do you need to define a decorator with parameters?
How many functions do you need to define a ordinary decorator?

How many functions do you need to define a ordinary decorator?

Виберіть правильну відповідь

How many functions do you need to define a decorator with parameters?

How many functions do you need to define a decorator with parameters?

Виберіть правильну відповідь

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 3. Розділ 5
some-alt