LearnFrenzy
Sign in Take a free test

Decorators · Decorators Coding Problems · Question 1

A call logger decorator showing arguments and results in Python Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

Write a decorator that prints each call with its positional and keyword arguments and the value returned.

Solution
main.py Run
from functools import wraps

def log_calls(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        parts = [repr(a) for a in args] + [f"{k}={v!r}" for k, v in kwargs.items()]
        result = func(*args, **kwargs)
        print(f"{func.__name__}({', '.join(parts)}) -> {result!r}")
        return result
    return wrapper

@log_calls
def ticket_price(base, seats=1, member=False):
    return base * seats * (0.9 if member else 1)

ticket_price(250)
ticket_price(250, 3, member=True)

Output Verified by running it on Python 3

ticket_price(250) -> 250
ticket_price(250, 3, member=True) -> 675.0

The wrapper builds a readable argument list from args and kwargs, then forwards both unchanged.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links