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 arguments
1def repeat(times):
# Actual decorator function takes the function
2 def decorator(func):
# Wrapper function replaces the original
3 def wrapper(*args, **kwargs):
# Execute function 'times' number of times
4 for _ in range(times):
# Call original function and store result
5 result = func(*args, **kwargs)
# Return the last result
6 return result
# Return the wrapper function
7 return wrapper
# Return the decorator
8 return decorator
9
# Apply decorator with argument 3
10@repeat(3)
# Define function to be decorated
11def greet(name):
# Print greeting message
12 print(f"Hello, {name}!")
13
# Call decorated function - prints 3 times
14greet("Alice")

Output

Hello, Alice!
Hello, Alice!
Hello, Alice!
Practice typing this code

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

More Python examples at level 5

← Python typing practice