Using functools.wraps in Python
Level 4239 keystrokes
This shows using @wraps to preserve function metadata in decorators. Without wraps, the decorated function loses its original name.
Python code
# wraps copies the original function's metadata onto the wrapper1from functools import wraps2 # Define a decorator that logs every call3def debug(func): # @wraps(func) keeps the original __name__ (and docstring) on wrapper4 @wraps(func) # wrapper accepts any positional and keyword arguments5 def wrapper(*args, **kwargs): # Print the name of the function being called: Calling greet6 print(f"Calling {func.__name__}") # Call the original function and pass its result through7 return func(*args, **kwargs) # The decorator returns wrapper in place of func8 return wrapper9 # Apply the decorator: same as greet = debug(greet)10@debug11def greet(name): # The original function builds the greeting12 return f"Hello, {name}!"13 # Prints "Calling greet" first, then "Hello, Alice!"14print(greet("Alice"))Output
Calling greet 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.
(× 8)× 8"× 6*× 6_× 4,× 3:× 3{× 2}× 2@× 2