decorators:
args + kwargs
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
If you're not familiar with args/kwargs you should check out the course on this topic here. Assuming you're familiar, we'll now make the functionality-adding function from the previous video better.
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
def sleep_random(s):
t = s + random.random()
time.sleep(t)
return "Done"
timed_sleep = stopwatch(sleep_random)
Again, now have two functions that are similar, but they now both allow for an input.
sleep_random(s=2)
timed_sleep(s=2)
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.