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

bookWriting Parameterized Decorators

Swipe to show menu

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()
copy

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?

Select the correct answer

question mark

Why might you want to pass arguments to a decorator?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 4. Chapter 3

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Section 4. Chapter 3
some-alt