Calmcode - decorators: args + kwargs

Args + Kwargs

1 2 3 4 5 6 7 8 9 10

If you're not familiar with args/kwargs you should check out the course on args and kwargs first. 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)