def — Advanced Playground
Defines a new function or method
Python Playground
import functools
def timer(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
import time
start = time.perf_counter()
result = func(*args, **kwargs)
elapsed = time.perf_counter() - start
print(f"{func.__name__} took {elapsed:.6f}s")
return result
return wrapper
@timer
def slow_sum(n):
"""Sum numbers from 0 to n."""
return sum(range(n))
result = slow_sum(1_000_000)
print(f"Result: {result}")
print(f"Docstring preserved: {slow_sum.__doc__}")
Output
Click "Run" to execute your code
Decorators use @syntax to wrap functions. functools.wraps preserves the original function's name and docstring on the wrapper.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?