Question presented to candidate:
"You see @something above function definitions all over Python code. What is a decorator, what does the @ line actually do, and can you write one for me, say one that logs or changes what a function returns?"
What a strong answer should cover:
- A decorator is a callable that takes a function (or class) and returns a replacement;
@decoabovedef fmeansf = deco(f), applied once when thedefstatement runs. - It works because functions are first-class objects and the inner wrapper is a closure that remembers the original function.
- The standard shape: an inner
wrapper(*args, **kwargs)that calls the original, returns its result, and is decorated withfunctools.wraps. - Stacking order: the decorator nearest the
defis applied first, the top one wraps everything (so it runs first at call time). - Real uses: logging, timing, caching (
functools.lru_cache), access checks, retries, registration (web routes, plugins),property/classmethod/staticmethod, and class decorators such asdataclasses.dataclass. - A version fact: function decorators came with PEP 318 (Python 2.4), class decorators with PEP 3129, and PEP 614 (Python 3.9) allows any expression after
@.
Code / implementation expected: Yes β write a small decorator (logging, timing or a result transform) live, with *args, **kwargs and functools.wraps.