logo

... decorators: wraps



Notes

Let's make sure that the docstring is kept intact by using @wraps.

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):
    """This function sleeps at least for `s` seconds."""
    return time.sleep(s + random.random())

timed_sleep = stopwatch(sleep_random)

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

help(sleep_random)

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.