Decorator with Arguments in Python
Level 5239 keystrokes
This creates a decorator that accepts arguments. The outer function takes the argument and returns the actual decorator.
Python code
# Outer function takes decorator arguments1def repeat(times): # Actual decorator function takes the function2 def decorator(func): # Wrapper function replaces the original3 def wrapper(*args, **kwargs): # Execute function 'times' number of times4 for _ in range(times): # Call original function and store result5 result = func(*args, **kwargs) # Return the last result6 return result # Return the wrapper function7 return wrapper # Return the decorator8 return decorator9 # Apply decorator with argument 310@repeat(3)# Define function to be decorated11def greet(name): # Print greeting message12 print(f"Hello, {name}!")13 # Call decorated function - prints 3 times14greet("Alice")Output
Hello, Alice! Hello, Alice! Hello, Alice!
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Python code and how often they appear.
(× 9)× 9*× 6:× 5"× 4,× 3_× 1!× 1{× 1}× 1