Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende Writing Parameterized Decorators | Mastering Python Decorators
Functional Programming Concepts in Python

Writing Parameterized Decorators

Desliza para mostrar el menú

When you want your decorator to behave differently depending on some input, you need to create a parameterized decorator. Unlike regular decorators, which only take the function as an argument, parameterized decorators accept their own arguments, allowing you to control their behavior dynamically. This is especially useful when you want to reuse a decorator in multiple situations with different configurations.

The Structure of a Parameterized Decorator:

  1. The outer function accepts the decorator arguments;
  2. The middle function is the actual decorator that takes the function to be decorated;
  3. The inner function wraps and controls the execution of the original function.

This layered approach lets you pass arguments to the decorator, which are then available when the decorated function is called.

12345678910111213141516171819202122
# Outer function: accepts the decorator argument 'times' def repeat(times): # The actual decorator that takes the function to be decorated def decorator(func): # Inner function: wraps and controls the execution of 'func' def wrapper(*args, **kwargs): result = None # Call the original function 'times' times for _ in range(times): result = func(*args, **kwargs) return result # Return the wrapper to replace the original function return wrapper # Return the decorator function return decorator # Apply the repeat decorator @repeat(3) def say_hello(): print("Hello!") say_hello()

1. How does a parameterized decorator differ from a regular decorator?

2. Why might you want to pass arguments to a decorator?

question mark

How does a parameterized decorator differ from a regular decorator?

Selecciona la respuesta correcta

question mark

Why might you want to pass arguments to a decorator?

Selecciona la respuesta correcta

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 4. Capítulo 3

Pregunte a AI

expand

Pregunte a AI

ChatGPT

Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla

Sección 4. Capítulo 3
some-alt