What are a decorator and a closure? Give an example of a decorator you wrote for production tasks.
Asked at
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.
Also asked at ГК МЕДСИ
- [name] asked: How does memory management work in Python (garbage collector, reference counting)?
- What is the difference between TaskGroup and the gather function in the asyncio library in Python?
- What solutions did you implement to work around ChatGPT being unavailable from Russian IP addresses?
- How do you scale web application workers (for example, in FastAPI or Django), and which server did you use on your project?
- What blocks the event loop, how do you detect it in production, and what should you do about blocking code?
Similar questions
- Write an example of a simple decorator in Python.
- What are decorators in Python, and what are they used for?
- Can you give a specific example from your work of using metaprogramming or decorators?
- Write a decorator that prints a function's arguments before calling it. How would you adapt it for an async function, apply it without @, and add type annotations?
- What is a decorator in Python? Have you used decorators in practice?