Medium: Interview Core · Problem 55 of 82

Log the Calls

MediumDecorators and AdvancedPython

Write a decorator log_calls. Each time the decorated function is called, it first prints one line, then calls the function and returns its result. The line looks like this, for add(1, b=3):

calling add(1, b=3)

Positional arguments are shown with repr, then keyword arguments as name=repr(value), separated by ", ". Strings therefore show their quotes: greet('Ann').

Understand the problem

Build the line by hand.

What is repr("Ann")? Type the result with its quotes.

repr gives text that looks like the code that would create the value, so a string keeps its quotes. str("Ann") would give Ann without quotes. For logging arguments, repr is what you want: you can see exactly what was passed.

How do you turn (1, "x") and {"b": 3} into the text 1, 'x', b=3?

  1. str(args) + str(kwargs)
  2. ", ".join([repr(a) for a in args] + [f"{k}={v!r}" for k, v in kwargs.items()])
  3. args + kwargs

Make a list of strings, one per argument (positional ones with repr, keyword ones as name=repr(value)), and join them with ", ". !r inside an f-string means "use repr".

Write the solution

Write the decorator.

def log_calls(func):
    # Write your code here.
    pass
Hint 1: a question to ask yourself

Where in the wrapper must the print happen, and what must the wrapper return?

Hint 2: the shape of the answer

Inner wrapper(*args, **kwargs): build the list of argument texts, print(f"calling {func.__name__}({...})"), then return func(*args, **kwargs). Add functools.wraps(func).

Reflect

Solution

import functools

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

What this tests: a decorator that adds behaviour around a call, repr versus str, building text with join, and passing the result on.

The classic bug: forgetting return in the wrapper, so every decorated function suddenly returns None. A decorator must be invisible to the caller.

Print versus logging: real code uses the logging module (levels, files, timestamps) instead of print. The decorator shape is identical.

Order of effects: this prints before the call, so you still see the line if the function raises. Printing after would lose it.

What an interviewer might ask next: Also log the result and the time taken. (Call the function in a variable, measure with time.perf_counter(), print, then return it.)