decorators:
wraps
Decorators are functions that make other functions better. It's a bit meta, but they're very powerful. In this series of video's we'll explore them by building our own but also by showing how you typically use them.
Notes
Let's make sure that the docstring is kept intact by using @wraps
.
import time
import random
def stopwatch(f):
def func(*args, **kwargs):
tic = time.time()
result = f(*args, **kwargs)
print(f"this function took: {time.time() - tic}")
return result
return func
@stopwatch
def sleep_random(s):
"""This function sleeps at least for `s` seconds."""
return time.sleep(s + random.random())
timed_sleep = stopwatch(sleep_random)
Note that we now no longer have two functions, but one!
help(sleep_random)
Feedback? See an issue? Something unclear? Feel free to mention it here.
If you want to be kept up to date, consider signing up for the newsletter.