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

Contenido del Curso

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:

1234567891011121314151617181920212223242526272829303132333435363738394041
admin = { "username": "john123.bra", "password": "secret333password", } def validate(func): def wrapper(user: dict, username: str, password: str) -> bool: validate_data = True if not isinstance(user, dict): validate_data = False if not user.get("username", False): validate_data = False if not user.get("password", False): validate_data = False if validate_data: return func(user, username, password) else: print("Wrong data!") return False return wrapper @validate def auth(user: dict, username: str, password: str) -> bool: if ( username == user["username"] and password == user["password"] ): print("User data is correct!") return True else: print("Wrong data!") return False print(auth(admin, "1231", "12512")) print(auth({1: 2}, "dsfs31", "safasf2")) print(auth(admin, "john123.bra", "secret333password",))
copy

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.

¿Todo estuvo claro?

Sección 3. Capítulo 2
We're sorry to hear that something went wrong. What happened?
some-alt