decorators logo decorators: decorate

1 2 3 4 5 6 7 8 9 10
Notes

We've seen how functions can accept functions and output functions. Hopefully it is clear that we can use this technique to add behavior to functions.

For better syntax, let's use the @ symbol to add behavior to a function.

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):
    t = s + random.random()
    time.sleep(t)
    return f"Done"

Note that we now no longer have two functions, both one!

sleep_random(1)
sleep_random(2)
sleep_random(3)