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

Зміст курсу

Mastering Python: Closures and Decorators

Mastering Python: Closures and Decorators

1. Scopes
2. Closure
3. Decorators

Flexible Decorators

Different functions require a varying number of arguments.

To create a decorator that can be applied to functions with varying numbers of arguments, you can use the *args and **kwargs as arguments in the wrapper() function.

Let's create an indicate decorator that prints information about the function execution:

  1. Print a message that the function has started execution.
  2. Print the arguments taken by the function.
  3. Call the function and save the result that is returned by the function.
  4. Print a message that the function has finished execution.
  5. Return the result.

The indicate() has the wrapper() that takes the *args and **kwargs. That means that wrapper() can take every number of arguments and keyword arguments.

The add_two() function takes 2 arguments.
The add_three() function takes 3 arguments.
The add_many_kwargs() takes a different number of keyword arguments.

The indicate() decorator can be used for every function.

So, the *args and **kwargs in the wrapper() allow us to use the decorator for any function.

Note

Remember to unpack the received args and kwargs using asterisks (* for args and ** for kwargs) when passing them to a nested function.
If you don't understand or have forgotten how to do this, feel free to come back here.

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

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