JuniorJunior (1–3 yrs)CodingPythonFastAPIAmazonUber
Decorators
Write and explain a parameterized decorator that measures execution time.
Answers use simple, clear English.
Quick interview answer
A parameterized decorator is a function returning a decorator. Use functools.wraps to preserve metadata. For async functions, detect coroutines and await inside the wrapper.
Detailed answer
A parameterized decorator is a function returning a decorator. Use functools.wraps to preserve metadata. For async functions, detect coroutines and await inside the wrapper.
Code example
import functools, time
def timed(label: str):
def deco(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
start = time.perf_counter()
try:
return fn(*args, **kwargs)
finally:
print(f"{label}: {time.perf_counter()-start:.4f}s")
return wrapper
return decoPractice code · python (view only · no execution)
import functools, time
def timed(label: str):
def deco(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
start = time.perf_counter()
try:
return fn(*args, **kwargs)
finally:
print(f"{label}: {time.perf_counter()-start:.4f}s")
return wrapper
return decofresherjuniormid#decorators