logo

... decorators: decorate



Notes

We can also use the decorator syntax to achieve the same behavior.

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)

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.