logo

... decorators: behavior



Notes

Let's combine the ideas from the previous video to create a function that accepts a function as input but also returns a function as output.

import time 
import random

def stopwatch(f):
    def func():
        tic = time.time()
        result = f()
        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)

You now have two functions that are similar, but also different.

sleep_random()
timed_sleep()

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.