NewWork mode: your Claude Code or Codex on work calls, answering from your project's codeSkip to content
Senior0 views

What are a decorator and a closure? Give an example of a decorator you wrote for production tasks.

Practice

AI answer

A closure is a function that retains access to variables from an outer scope even after the outer function has finished executing. A decorator is a function that takes another function and returns a wrapper for it, adding behavior without changing the original code. For example, in production, a decorator can measure the duration of a call; it is important to preserve metadata using functools.wraps:

from functools import wraps
from time import perf_counter


def timed(metric):
    def decorate(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            start = perf_counter()
            try:
                return func(*args, **kwargs)
            finally:
                metric.observe(perf_counter() - start)
        return wrapper
    return decorate

Here, decorate closes over metric, while wrapper closes over func and metric. In an actual answer, you should mention a decorator and a task that you have really implemented.