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 wrapper
1from functools import wraps
2
# Define a decorator that logs every call
3def debug(func):
# @wraps(func) keeps the original __name__ (and docstring) on wrapper
4 @wraps(func)
# wrapper accepts any positional and keyword arguments
5 def wrapper(*args, **kwargs):
# Print the name of the function being called: Calling greet
6 print(f"Calling {func.__name__}")
# Call the original function and pass its result through
7 return func(*args, **kwargs)
# The decorator returns wrapper in place of func
8 return wrapper
9
# Apply the decorator: same as greet = debug(greet)
10@debug
11def greet(name):
# The original function builds the greeting
12 return f"Hello, {name}!"
13
# Prints "Calling greet" first, then "Hello, Alice!"
14print(greet("Alice"))

Output

Calling greet
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.

  • (× 8
  • )× 8
  • "× 6
  • *× 6
  • _× 4
  • ,× 3
  • :× 3
  • {× 2
  • }× 2
  • @× 2

More Python examples at level 4

← Python typing practice