Write a Logging Decorator
Advanced · Write the code · from Python Decorators Explained: A Step-by-Step Guide
From the lesson: Why Do You Need functools.wraps?
There's a subtle problem with basic decorators. When you replace a function with a wrapper, the wrapper has a different name and docstring. This makes debugging confusing.
Read this part of the lessonWrite a decorator called log_call that prints the function name and arguments before calling the function, then prints the return value after.
Use functools.wraps. Expected behavior:
@log_call
def add(a, b):
return a + b
result = add(3, 4)Should print:
Calling add(3, 4)
add returned 7from functools import wraps
def log_call(func):
# Write your decorator here
pass
@log_call
def add(a, b):
return a + b
result = add(3, 4)
More Decorator exercises
- Predict the Decorator OutputIntermediate
- Write a Repeat DecoratorAdvanced
- Predict Stacked Decorator OutputAdvanced
- Write a Validation DecoratorAdvanced
- Write a Retry DecoratorAdvanced
- Fix the Broken DecoratorIntermediate
- Build a Simple Cache DecoratorAdvanced
All Python exercises · 50 practice problems · Advanced Python quiz