Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Decorator Usage | 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 Usage

The syntax add = decorator(add) after the function definition is not optimal. Python allows for a simpler way of using decorators:

It works as follows:

Note

The @ symbol is syntactic sugar.
Syntactic sugar is a programming language toolkit that makes writing code easier or better.

Decorator Usage

Decorators can have any prescribed logic and be used for different situations. Here are some examples of useful decorators:

  • Timing Decorator: A decorator that measures the time taken to execute a function.
  • Logging Decorator: A decorator that logs the output of a function.
  • Validation Decorator: A decorator that validates the input parameters of a function before execution.

Let's implement the validation decorator for this function:

In the auth() function, the argument user is expected to be a dictionary with keys "username" and "password", and other parameters are of type string.

The validation decorator should look like this:

In the example above, the @validate decorator wraps the auth function and prepares the wrapper actions for every call to the auth function. If the taken values are valid, the if validate_data code block should execute the enclosed func (auth) function and return the result. This way, we have no errors even if we pass an incorrect dictionary to the auth function.

The username and password do not require validation because the == comparison does not raise any errors. It always returns False if the data is unequal, regardless of the data types.

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

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