Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Decorators with Parameters | Decorators
Intermediate Python: Arguments, Scopes and Decorators
course content

Conteúdo do Curso

Intermediate Python: Arguments, Scopes and Decorators

Intermediate Python: Arguments, Scopes and Decorators

1. Packing and Unpacking
2. Arguments in Function
3. Function as an Argument
4. Variable Scope
5. Decorators

bookDecorators with Parameters

Decorators with parameters in Python are an advanced feature that allow you to pass additional arguments to your decorators, enhancing their flexibility. Here's a practical example to illustrate this concept:

Basic Decorator Structure

First, let's start with a basic decorator structure:

123456789101112
def simple_decorator(func): def wrapper(): print("Something is happening before the function is called.") func() print("Something is happening after the function is called.") return wrapper @simple_decorator def say_hello(): print("Hello!") say_hello()
copy

In this example, simple_decorator is a regular decorator that modifies the behavior of the say_hello function.

Decorator with Parameters

Now, let's create a decorator that accepts parameters:

12345678910111213
def decorator_with_args(arg1, arg2): def decorator(func): def wrapper(*args, **kwargs): print(f"Decorator args: {arg1}, {arg2}") return func(*args, **kwargs) return wrapper return decorator @decorator_with_args("hello", 42) def print_numbers(a, b): print(a + b) print_numbers(10, 5)
copy

In this example, decorator_with_args is a decorator factory that accepts parameters (arg1, arg2) and returns the actual decorator (decorator). The wrapper function is the one that modifies the behavior of the decorated function (print_numbers).

Explanation

  • decorator_with_args is called with its arguments ("hello", 42);
  • It returns the decorator function;
  • decorator takes a function print_numbers and returns the wrapper function;
  • wrapper has access to both the arguments of decorator_with_args and the arguments of print_numbers.

This structure allows for greater flexibility and reusability of decorators, as you can pass custom arguments to modify their behavior.

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 5. Capítulo 4
some-alt