Editor

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 lesson

Write 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 7
from 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

All Python exercises · 50 practice problems · Advanced Python quiz