Calmcode - decorators: behavior

Behavior

1 2 3 4 5 6 7 8 9 10

We've seen how functions can accept functions in python as input. Let's use this knowledge 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():
    time.sleep(random.random())
    return "Done!"

timed_sleep = stopwatch(sleep_random)

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

sleep_random()
timed_sleep()