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

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

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 decorator with parameters?

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

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

Секція 3. Розділ 5
We're sorry to hear that something went wrong. What happened?
some-alt