import functools
import time
deftimer(func):
@functools.wraps(func)defwrapper(*args,**kwargs):
start = time.perf_counter()
result =func(*args,**kwargs)
elapsed = time.perf_counter()- start
print(f"{func.__name__} took {elapsed:.4f}s")return result
return wrapper
@timer
defcompute(n):returnsum(range(n))compute(1_000_000)
Output
compute took 0.0XXXs
Note Always use @functools.wraps(func) in your wrapper so that the decorated function preserves its name and docstring. Decorators run at import time.
Frequently asked questions
How does JavaScript handle function wrapper?
This task is covered in 2 stacks on this page: JavaScript, Python. The "Higher-Order Functions" snippet in JavaScript uses `function fn(callback) { callback(); }`.
Which code does the JavaScript example use?
The "Higher-Order Functions" snippet uses `function fn(callback) { callback(); }`, from the Functions section of the JavaScript cheat sheet.
Which stacks cover "function wrapper" on this page?
JavaScript, Python. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Higher-Order Functions": Functions that accept or return other functions. The backbone of functional patterns like decorators, middleware, and composition.