Advertisement
Beginner Python, Decorators

How do you write a basic decorator that adds a print statement before and after calling the decorated function?

Short answer

Define an outer function taking the target function as its parameter, define an inner 'wrapper' function that prints, calls the original function, and returns its result, then return the wrapper — the wrapper REPLACES the original function.

Save Python mock interview
Advertisement
AModel answer
Define an outer function taking the target function as its parameter, define an inner 'wrapper' function that prints, calls the original function, and returns its result, then return the wrapper — the wrapper REPLACES the original function.
def logged(func):
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__}")
        result = func(*args, **kwargs)
        print(f"{func.__name__} finished")
        return result
    return wrapper

@logged
def add(a, b):
    return a + b

add(2, 3)  # prints 'Calling add', then 'add finished'
Real-world example
Adding consistent logging around every call to a specific function without repeating the print statements manually each time.
Likely follow-ups
  • Why does the wrapper function need to accept *args and **kwargs instead of specific named parameters?
Related topics